comment stringlengths 1 45k | method_body stringlengths 23 281k | target_code stringlengths 0 5.16k | method_body_after stringlengths 12 281k | context_before stringlengths 8 543k | context_after stringlengths 8 543k |
|---|---|---|---|---|---|
Consider adding a metric with the same name as an existing metric but different labels to test that these are emitted as distinct samples but grouped under the same metric `TYPE`/`HELP`. | public void testPrometheusFormat() {
var counterContext = StateMetricContext.newInstance(Map.of("label1", "val1", "label2", "val2"));
var snapshot = new MetricSnapshot(0L, SNAPSHOT_INTERVAL, TimeUnit.MILLISECONDS);
snapshot.set(null, "bar", 20);
snapshot.set(null, "bar", 40);
snapshot.add(counterContext, "some.counter"... | some_counter_count{label1="val1",label2="val2",} 30 300000 | public void testPrometheusFormat() {
var counterContext = StateMetricContext.newInstance(Map.of("label1", "val1", "label2", "val2"));
var snapshot = new MetricSnapshot(0L, SNAPSHOT_INTERVAL, TimeUnit.MILLISECONDS);
snapshot.set(null, "bar", 20);
snapshot.set(null, "bar", 40);
snapshot.add(counterContext, "some.counter"... | class StateHandlerTest extends StateHandlerTestBase {
private static final String V1_URI = URI_BASE + "/state/v1/";
private static StateHandler stateHandler;
@BeforeEach
public void setupHandler() {
stateHandler = new StateHandler(monitor, timer, applicationMetadataConfig, snapshotProviderRegistry);
testDriver = new Re... | class StateHandlerTest extends StateHandlerTestBase {
private static final String V1_URI = URI_BASE + "/state/v1/";
private static StateHandler stateHandler;
@BeforeEach
public void setupHandler() {
stateHandler = new StateHandler(monitor, timer, applicationMetadataConfig, snapshotProviderRegistry);
testDriver = new Re... |
Is it required to emit a `HELP` line for each metric even if the associated docstring is empty? The `simpleclient` `TextFormat` implementation seems to do this, but I can't find anything in the exposition docs that imply it's actually required. Less fluff on the wire is always a good thing 👀 | private void appendPrometheusEntry(StringBuilder builder, String metricName, String dimension, Number value, long timeStamp) {
builder.append("
.append(metricName)
.append("\n
.append(metricName)
.append(" untyped\n");
builder.append(metricName)
.append("{").append(dimension).append("}")
.append(" ").append(sanitizeIfD... | .append(metricName) | private void appendPrometheusEntry(StringBuilder builder, String metricName, String dimension, Number value, long timeStamp) {
builder.append("
.append(metricName)
.append("\n
.append(metricName)
.append(" untyped\n");
builder.append(metricName)
.append("{").append(dimension).append("}")
.append(" ").append(sanitizeIfD... | class MyContentChannel implements ContentChannel {
private final List<ByteBuffer> buffers;
private final Runnable trigger;
@Override
public void write(ByteBuffer buf, CompletionHandler handler) {
buffers.add(buf);
if (handler != null) handler.completed();
}
@Override
public void close(CompletionHandler handler) {
trigg... | class MyContentChannel implements ContentChannel {
private final List<ByteBuffer> buffers;
private final Runnable trigger;
@Override
public void write(ByteBuffer buf, CompletionHandler handler) {
buffers.add(buf);
if (handler != null) handler.completed();
}
@Override
public void close(CompletionHandler handler) {
trigg... |
I think we might want to skip emitting braces entirely if the set of labels is empty for a given metric. The [exposition EBNF](https://prometheus.io/docs/instrumenting/exposition_formats/#comments-help-text-and-type-information) implies that at least one key/value pair should be present if braces are present: ``` metri... | private void appendPrometheusEntry(StringBuilder builder, String metricName, String dimension, Number value, long timeStamp) {
builder.append("
.append(metricName)
.append("\n
.append(metricName)
.append(" untyped\n");
builder.append(metricName)
.append("{").append(dimension).append("}")
.append(" ").append(sanitizeIfD... | .append("{").append(dimension).append("}") | private void appendPrometheusEntry(StringBuilder builder, String metricName, String dimension, Number value, long timeStamp) {
builder.append("
.append(metricName)
.append("\n
.append(metricName)
.append(" untyped\n");
builder.append(metricName)
.append("{").append(dimension).append("}")
.append(" ").append(sanitizeIfD... | class MyContentChannel implements ContentChannel {
private final List<ByteBuffer> buffers;
private final Runnable trigger;
@Override
public void write(ByteBuffer buf, CompletionHandler handler) {
buffers.add(buf);
if (handler != null) handler.completed();
}
@Override
public void close(CompletionHandler handler) {
trigg... | class MyContentChannel implements ContentChannel {
private final List<ByteBuffer> buffers;
private final Runnable trigger;
@Override
public void write(ByteBuffer buf, CompletionHandler handler) {
buffers.add(buf);
if (handler != null) handler.completed();
}
@Override
public void close(CompletionHandler handler) {
trigg... |
Unless `entry.getValue()` is pre-sanitized we might want to add some escaping here to ensure our label values are always edible: > `label_value` can be any sequence of UTF-8 characters, but the backslash (`\`), double-quote (`"`), and line feed (`\n`) characters have to be escaped as `\\`, `\"`, and `\n`, respectively | private String toPrometheusDimensions(MetricDimensions dimensions) {
if (dimensions == null) return "";
StringBuilder builder = new StringBuilder();
dimensions.forEach(entry -> {
var sanitized = prometheusSanitizedName(entry.getKey()) + "=\"" + entry.getValue() + "\",";
builder.append(sanitized);
});
return builder.toS... | var sanitized = prometheusSanitizedName(entry.getKey()) + "=\"" + entry.getValue() + "\","; | private String toPrometheusDimensions(MetricDimensions dimensions) {
if (dimensions == null) return "";
StringBuilder builder = new StringBuilder();
dimensions.forEach(entry -> {
var sanitized = prometheusSanitizedName(entry.getKey()) + "=\"" + entry.getValue() + "\",";
builder.append(sanitized);
});
return builder.toS... | class MyContentChannel implements ContentChannel {
private final List<ByteBuffer> buffers;
private final Runnable trigger;
@Override
public void write(ByteBuffer buf, CompletionHandler handler) {
buffers.add(buf);
if (handler != null) handler.completed();
}
@Override
public void close(CompletionHandler handler) {
trigg... | class MyContentChannel implements ContentChannel {
private final List<ByteBuffer> buffers;
private final Runnable trigger;
@Override
public void write(ByteBuffer buf, CompletionHandler handler) {
buffers.add(buf);
if (handler != null) handler.completed();
}
@Override
public void close(CompletionHandler handler) {
trigg... |
If my understanding of `collapseMetrics` _and_ the [Prometheus exposition docs](https://prometheus.io/docs/instrumenting/exposition_formats/#grouping-and-sorting) is correct, I think we need to add an extra aggregation step that groups all samples for the same metric _name_ under the same `HELP`/`TYPE` umbrella: > All... | private byte[] buildPrometheusForConsumer(String consumer) {
var snapshot = getSnapshot();
if (snapshot == null)
return new byte[0];
var timestamp = snapshot.getToTime(TimeUnit.MILLISECONDS);
var builder = new StringBuilder();
builder.append("
for (var tuple : collapseMetrics(snapshot, consumer)) {
var dims = toPrometh... | for (var tuple : collapseMetrics(snapshot, consumer)) { | private byte[] buildPrometheusForConsumer(String consumer) {
var snapshot = getSnapshot();
if (snapshot == null)
return new byte[0];
var timestamp = snapshot.getToTime(TimeUnit.MILLISECONDS);
var builder = new StringBuilder();
builder.append("
for (var tuple : collapseMetrics(snapshot, consumer)) {
var dims = toPrometh... | class MyContentChannel implements ContentChannel {
private final List<ByteBuffer> buffers;
private final Runnable trigger;
@Override
public void write(ByteBuffer buf, CompletionHandler handler) {
buffers.add(buf);
if (handler != null) handler.completed();
}
@Override
public void close(CompletionHandler handler) {
trigg... | class MyContentChannel implements ContentChannel {
private final List<ByteBuffer> buffers;
private final Runnable trigger;
@Override
public void write(ByteBuffer buf, CompletionHandler handler) {
buffers.add(buf);
if (handler != null) handler.completed();
}
@Override
public void close(CompletionHandler handler) {
trigg... |
Configservers upgrade one-by-one, so you have to keep writing the field until there are no readers left. Stop reading the field first. Once that change has rolled out you can stop writing it and remove it entirely. | private static void toSlime(Cluster cluster, Cursor clusterObject) {
clusterObject.setBool(exclusiveKey, cluster.exclusive());
toSlime(cluster.minResources(), clusterObject.setObject(minResourcesKey));
toSlime(cluster.maxResources(), clusterObject.setObject(maxResourcesKey));
toSlime(cluster.groupSize(), clusterObject.... | if (! cluster.clusterInfo().isEmpty()) | private static void toSlime(Cluster cluster, Cursor clusterObject) {
clusterObject.setBool(exclusiveKey, cluster.exclusive());
toSlime(cluster.minResources(), clusterObject.setObject(minResourcesKey));
toSlime(cluster.maxResources(), clusterObject.setObject(maxResourcesKey));
toSlime(cluster.groupSize(), clusterObject.... | class ApplicationSerializer {
private static final String idKey = "id";
private static final String statusKey = "status";
private static final String currentReadShareKey = "currentReadShare";
private static final String maxReadShareKey = "maxReadShare";
private static final String clustersKey = "clusters";
private stat... | class ApplicationSerializer {
private static final String idKey = "id";
private static final String statusKey = "status";
private static final String currentReadShareKey = "currentReadShare";
private static final String maxReadShareKey = "maxReadShare";
private static final String clustersKey = "clusters";
private stat... |
done, PTAL | private void validate(Map<String, String> properties) throws DdlException {
if (properties == null) {
throw new DdlException("Please set properties of hive table, "
+ "they are: database, table and resource");
}
Map<String, String> copiedProps = Maps.newHashMap(properties);
hiveDb = copiedProps.get(HIVE_DB);
if (String... | if (!Strings.isNullOrEmpty(resourceName)) { | private void validate(Map<String, String> properties) throws DdlException {
if (properties == null) {
throw new DdlException("Please set properties of hive table, "
+ "they are: database, table and resource");
}
Map<String, String> copiedProps = Maps.newHashMap(properties);
hiveDb = copiedProps.get(HIVE_DB);
if (String... | class HiveTable extends Table {
private static final Logger LOG = LogManager.getLogger(HiveTable.class);
private static final String PROPERTY_MISSING_MSG =
"Hive %s is null. Please add properties('%s'='xxx') when create table";
private static final String JSON_KEY_HIVE_DB = "hiveDb";
private static final String JSON_KE... | class HiveTable extends Table {
private static final Logger LOG = LogManager.getLogger(HiveTable.class);
private static final String PROPERTY_MISSING_MSG =
"Hive %s is null. Please add properties('%s'='xxx') when create table";
private static final String JSON_KEY_HIVE_DB = "hiveDb";
private static final String JSON_KE... |
Was logging in the middle of the state transition intentional? | public void processMessage(Message message) {
super.processMessage(message);
if (++numSent < windowSize * resizeRate) {
return;
}
long time = timer.milliTime();
double elapsed = time - resizeTime;
resizeTime = time;
double throughput = numOk / elapsed;
numSent = 0;
numOk = 0;
if (maxThroughput > 0 && throughput > maxTh... | log.log(Level.FINE, () -> "windowSize " + windowSize + " throughput " + throughput + " local max " + localMaxThroughput); | public void processMessage(Message message) {
super.processMessage(message);
if (++numSent < windowSize * resizeRate) {
return;
}
long time = timer.milliTime();
double elapsed = time - resizeTime;
resizeTime = time;
double throughput = numOk / elapsed;
numSent = 0;
numOk = 0;
if (maxThroughput > 0 && throughput > maxTh... | class using the given clock to calculate efficiency.
*
* @param timer the timer to use
*/
public DynamicThrottlePolicy(Timer timer) {
this.timer = timer;
this.timeOfLastMessage = timer.milliTime();
} | class using the given clock to calculate efficiency.
*
* @param timer the timer to use
*/
public DynamicThrottlePolicy(Timer timer) {
this.timer = timer;
this.timeOfLastMessage = timer.milliTime();
} |
Yes, need to print old **localMaxThroughput** before it is set equal to **throughput** | public void processMessage(Message message) {
super.processMessage(message);
if (++numSent < windowSize * resizeRate) {
return;
}
long time = timer.milliTime();
double elapsed = time - resizeTime;
resizeTime = time;
double throughput = numOk / elapsed;
numSent = 0;
numOk = 0;
if (maxThroughput > 0 && throughput > maxTh... | log.log(Level.FINE, () -> "windowSize " + windowSize + " throughput " + throughput + " local max " + localMaxThroughput); | public void processMessage(Message message) {
super.processMessage(message);
if (++numSent < windowSize * resizeRate) {
return;
}
long time = timer.milliTime();
double elapsed = time - resizeTime;
resizeTime = time;
double throughput = numOk / elapsed;
numSent = 0;
numOk = 0;
if (maxThroughput > 0 && throughput > maxTh... | class using the given clock to calculate efficiency.
*
* @param timer the timer to use
*/
public DynamicThrottlePolicy(Timer timer) {
this.timer = timer;
this.timeOfLastMessage = timer.milliTime();
} | class using the given clock to calculate efficiency.
*
* @param timer the timer to use
*/
public DynamicThrottlePolicy(Timer timer) {
this.timer = timer;
this.timeOfLastMessage = timer.milliTime();
} |
There is a `HttpRequest` constructor taking timestamp as nano seconds. Consider adding a new `RequestHandlerTestDriver.sendRequest()` overload with timestamp. That way we can lower the test cost by a couple of magnitudes ;) | public void testOverLoadByAge() {
RequestHandlerTestDriver driver = new RequestHandlerTestDriver(handler);
access.session.expect((id, parameters) -> new Result(Result.ResultType.TRANSIENT_ERROR, Result.toError(Result.ResultType.TRANSIENT_ERROR)));
var response1 = driver.sendRequest("http:
try { Thread.sleep(3_000); } c... | try { Thread.sleep(3_000); } catch (InterruptedException e) {} | public void testOverLoadByAge() {
RequestHandlerTestDriver driver = new RequestHandlerTestDriver(handler);
access.session.expect((id, parameters) -> new Result(Result.ResultType.TRANSIENT_ERROR, Result.toError(Result.ResultType.TRANSIENT_ERROR)));
var response1 = driver.sendRequest("http:
try { Thread.sleep(3_000); } c... | class DocumentV1ApiTest {
final AllClustersBucketSpacesConfig bucketConfig = new AllClustersBucketSpacesConfig.Builder()
.cluster("content",
new AllClustersBucketSpacesConfig.Cluster.Builder()
.documentType("music",
new AllClustersBucketSpacesConfig.Cluster.DocumentType.Builder()
.bucketSpace(FixedBucketSpaces.defaultS... | class DocumentV1ApiTest {
final AllClustersBucketSpacesConfig bucketConfig = new AllClustersBucketSpacesConfig.Builder()
.cluster("content",
new AllClustersBucketSpacesConfig.Cluster.Builder()
.documentType("music",
new AllClustersBucketSpacesConfig.Cluster.DocumentType.Builder()
.bucketSpace(FixedBucketSpaces.defaultS... |
should we add UT in `LeaderOpExecutorTest.java` | private void forward() throws Exception {
int forwardTimes = ctx.getForwardTimes() + 1;
if (forwardTimes > 1) {
LOG.info("forward multi times: {}", forwardTimes);
}
if (forwardTimes > MAX_FORWARD_TIMES) {
LOG.warn("too many forward times, max allowed forward time is {}", MAX_FORWARD_TIMES);
ErrorReportException.report(... | params.setWarehouse_id(ctx.getCurrentWarehouseId()); | private void forward() throws Exception {
int forwardTimes = ctx.getForwardTimes() + 1;
if (forwardTimes > 1) {
LOG.info("forward multi times: {}", forwardTimes);
}
if (forwardTimes > MAX_FORWARD_TIMES) {
LOG.warn("too many forward times, max allowed forward time is {}", MAX_FORWARD_TIMES);
ErrorReportException.report(... | class LeaderOpExecutor {
private static final Logger LOG = LogManager.getLogger(LeaderOpExecutor.class);
public static final int MAX_FORWARD_TIMES = 30;
private final OriginStatement originStmt;
private StatementBase parsedStmt;
private final ConnectContext ctx;
private TMasterOpResult result;
private int waitTimeoutMs... | class LeaderOpExecutor {
private static final Logger LOG = LogManager.getLogger(LeaderOpExecutor.class);
public static final int MAX_FORWARD_TIMES = 30;
private final OriginStatement originStmt;
private StatementBase parsedStmt;
private final ConnectContext ctx;
private TMasterOpResult result;
private int waitTimeoutMs... |
But that is not the same timestamp as `private final long jvmRelativeCreatedAt = System.nanoTime();` | public void testOverLoadByAge() {
RequestHandlerTestDriver driver = new RequestHandlerTestDriver(handler);
access.session.expect((id, parameters) -> new Result(Result.ResultType.TRANSIENT_ERROR, Result.toError(Result.ResultType.TRANSIENT_ERROR)));
var response1 = driver.sendRequest("http:
try { Thread.sleep(3_000); } c... | try { Thread.sleep(3_000); } catch (InterruptedException e) {} | public void testOverLoadByAge() {
RequestHandlerTestDriver driver = new RequestHandlerTestDriver(handler);
access.session.expect((id, parameters) -> new Result(Result.ResultType.TRANSIENT_ERROR, Result.toError(Result.ResultType.TRANSIENT_ERROR)));
var response1 = driver.sendRequest("http:
try { Thread.sleep(3_000); } c... | class DocumentV1ApiTest {
final AllClustersBucketSpacesConfig bucketConfig = new AllClustersBucketSpacesConfig.Builder()
.cluster("content",
new AllClustersBucketSpacesConfig.Cluster.Builder()
.documentType("music",
new AllClustersBucketSpacesConfig.Cluster.DocumentType.Builder()
.bucketSpace(FixedBucketSpaces.defaultS... | class DocumentV1ApiTest {
final AllClustersBucketSpacesConfig bucketConfig = new AllClustersBucketSpacesConfig.Builder()
.cluster("content",
new AllClustersBucketSpacesConfig.Cluster.Builder()
.documentType("music",
new AllClustersBucketSpacesConfig.Cluster.DocumentType.Builder()
.bucketSpace(FixedBucketSpaces.defaultS... |
Okay, in that case we need another overload for `HttpRequest`. | public void testOverLoadByAge() {
RequestHandlerTestDriver driver = new RequestHandlerTestDriver(handler);
access.session.expect((id, parameters) -> new Result(Result.ResultType.TRANSIENT_ERROR, Result.toError(Result.ResultType.TRANSIENT_ERROR)));
var response1 = driver.sendRequest("http:
try { Thread.sleep(3_000); } c... | try { Thread.sleep(3_000); } catch (InterruptedException e) {} | public void testOverLoadByAge() {
RequestHandlerTestDriver driver = new RequestHandlerTestDriver(handler);
access.session.expect((id, parameters) -> new Result(Result.ResultType.TRANSIENT_ERROR, Result.toError(Result.ResultType.TRANSIENT_ERROR)));
var response1 = driver.sendRequest("http:
try { Thread.sleep(3_000); } c... | class DocumentV1ApiTest {
final AllClustersBucketSpacesConfig bucketConfig = new AllClustersBucketSpacesConfig.Builder()
.cluster("content",
new AllClustersBucketSpacesConfig.Cluster.Builder()
.documentType("music",
new AllClustersBucketSpacesConfig.Cluster.DocumentType.Builder()
.bucketSpace(FixedBucketSpaces.defaultS... | class DocumentV1ApiTest {
final AllClustersBucketSpacesConfig bucketConfig = new AllClustersBucketSpacesConfig.Builder()
.cluster("content",
new AllClustersBucketSpacesConfig.Cluster.Builder()
.documentType("music",
new AllClustersBucketSpacesConfig.Cluster.DocumentType.Builder()
.bucketSpace(FixedBucketSpaces.defaultS... |
```suggestion throw new DdlException(“fail to refresh materialized views when dropping partition”, e); ``` | public void dropPartition(Database db, Table table, DropPartitionClause clause) throws DdlException {
OlapTable olapTable = (OlapTable) table;
Preconditions.checkArgument(db.isWriteLockHeldByCurrentThread());
String partitionName = clause.getPartitionName();
boolean isTempPartition = clause.isTempPartition();
if (olapT... | throw new DdlException(e.getMessage()); | public void dropPartition(Database db, Table table, DropPartitionClause clause) throws DdlException {
OlapTable olapTable = (OlapTable) table;
Preconditions.checkArgument(db.isWriteLockHeldByCurrentThread());
String partitionName = clause.getPartitionName();
boolean isTempPartition = clause.isTempPartition();
if (olapT... | class LocalMetastore implements ConnectorMetadata {
private static final Logger LOG = LogManager.getLogger(LocalMetastore.class);
private final ConcurrentHashMap<Long, Database> idToDb = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Database> fullNameToDb = new ConcurrentHashMap<>();
private Cluste... | class LocalMetastore implements ConnectorMetadata {
private static final Logger LOG = LogManager.getLogger(LocalMetastore.class);
private final ConcurrentHashMap<Long, Database> idToDb = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Database> fullNameToDb = new ConcurrentHashMap<>();
private Cluste... |
Test that the component is configured. The test now only checks that there is a container cluster. | void testIndexGreaterThanNumNodes() {
VespaModel vespaModel = createModel("src/test/cfg/significance");
ApplicationContainerCluster containerCluster = vespaModel.getContainerClusters().get("container");
assertEquals(1, containerCluster.getContainers().size());
} | assertEquals(1, containerCluster.getContainers().size()); | void testIndexGreaterThanNumNodes() {
VespaModel vespaModel = createModel("src/test/cfg/significance");
ApplicationContainerCluster containerCluster = vespaModel.getContainerClusters().get("container");
assertEquals(1, containerCluster.getContainers().size());
} | class SignificanceModelTestCase {
private VespaModel createModel(String filename) {
return new VespaModelCreatorWithFilePkg(filename).create();
}
@Test
} | class SignificanceModelTestCase {
private VespaModel createModel(String filename) {
return new VespaModelCreatorWithFilePkg(filename).create();
}
@Test
@Test
void testSignificance() {
VespaModel vespaModel = createModel("src/test/cfg/significance");
ApplicationContainerCluster containerCluster = vespaModel.getContainer... |
Added another test for this | void testIndexGreaterThanNumNodes() {
VespaModel vespaModel = createModel("src/test/cfg/significance");
ApplicationContainerCluster containerCluster = vespaModel.getContainerClusters().get("container");
assertEquals(1, containerCluster.getContainers().size());
} | assertEquals(1, containerCluster.getContainers().size()); | void testIndexGreaterThanNumNodes() {
VespaModel vespaModel = createModel("src/test/cfg/significance");
ApplicationContainerCluster containerCluster = vespaModel.getContainerClusters().get("container");
assertEquals(1, containerCluster.getContainers().size());
} | class SignificanceModelTestCase {
private VespaModel createModel(String filename) {
return new VespaModelCreatorWithFilePkg(filename).create();
}
@Test
} | class SignificanceModelTestCase {
private VespaModel createModel(String filename) {
return new VespaModelCreatorWithFilePkg(filename).create();
}
@Test
@Test
void testSignificance() {
VespaModel vespaModel = createModel("src/test/cfg/significance");
ApplicationContainerCluster containerCluster = vespaModel.getContainer... |
Consider specifying `JsonCreator` annotation for both types. FYI it's possible to use a Java record in combination with Jackson annotations. | public Role(@JsonProperty("name") String name, @JsonProperty("members") List<String> members) {
this.name = name;
this.members = members;
} | this.members = members; | public Role(@JsonProperty("name") String name, @JsonProperty("members") List<String> members) {
this.name = name;
this.members = members;
} | class Role {
@JsonProperty("name")
private final String name;
@JsonProperty("members")
private final List<String> members;
public String getName() {
return name;
}
public List<String> getMembers() {
return members;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != ... | class Role {
@JsonProperty("name")
private final String name;
@JsonProperty("members")
private final List<String> members;
@JsonCreator
public String getName() {
return name;
}
public List<String> getMembers() {
return members;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || g... |
Consider simplifying by using Junit5's `assertThrows` instead of the try-catch-fail pattern. | void invalid_url(){
var xml = """
<component id="bert-embedder" type="bert-embedder">
<transformer-model url="models/e5-base-v2.onnx" />
<tokenizer-vocab path="models/vocab.txt"/>
</component>
""";
try {
var state = new DeployState.Builder().build();
Model.fromXml(state, XML.getDocument(xml).getDocumentElement(), "tran... | try { | void invalid_url(){
var xml = """
<component id="bert-embedder" type="bert-embedder">
<transformer-model url="models/e5-base-v2.onnx" />
<tokenizer-vocab path="models/vocab.txt"/>
</component>
""";
var state = new DeployState.Builder().build();
var element = XML.getDocument(xml).getDocumentElement();
var exception = as... | class ModelTest {
@Test
} | class ModelTest {
@Test
} |
Good idea, done | void invalid_url(){
var xml = """
<component id="bert-embedder" type="bert-embedder">
<transformer-model url="models/e5-base-v2.onnx" />
<tokenizer-vocab path="models/vocab.txt"/>
</component>
""";
try {
var state = new DeployState.Builder().build();
Model.fromXml(state, XML.getDocument(xml).getDocumentElement(), "tran... | try { | void invalid_url(){
var xml = """
<component id="bert-embedder" type="bert-embedder">
<transformer-model url="models/e5-base-v2.onnx" />
<tokenizer-vocab path="models/vocab.txt"/>
</component>
""";
var state = new DeployState.Builder().build();
var element = XML.getDocument(xml).getDocumentElement();
var exception = as... | class ModelTest {
@Test
} | class ModelTest {
@Test
} |
```suggestion var exception = assertThrows(IllegalArgumentException.class, () -> Model.fromXml(state, element, "transformer-model", Set.of())); org.junit.jupiter.api.Assertions.assertEquals("Invalid url 'models/e5-base-v2.onnx': url has no 'scheme' component", exception.getMessage()); ... | void invalid_url(){
var xml = """
<component id="bert-embedder" type="bert-embedder">
<transformer-model url="models/e5-base-v2.onnx" />
<tokenizer-vocab path="models/vocab.txt"/>
</component>
""";
var state = new DeployState.Builder().build();
var element = XML.getDocument(xml).getDocumentElement();
assertThrows(Illeg... | "Invalid url 'models/e5-base-v2.onnx': url has no 'scheme' component"); | void invalid_url(){
var xml = """
<component id="bert-embedder" type="bert-embedder">
<transformer-model url="models/e5-base-v2.onnx" />
<tokenizer-vocab path="models/vocab.txt"/>
</component>
""";
var state = new DeployState.Builder().build();
var element = XML.getDocument(xml).getDocumentElement();
var exception = as... | class ModelTest {
@Test
} | class ModelTest {
@Test
} |
This will throw if not 228 has been executed in a previously iteration. Just initializing the variable with `null` will make it easier to identify these kind of bugs. | private static List<SearchChainInvocationSpec> extractSpecs(List<ResolveResult> results) {
List<SearchChainInvocationSpec> errors = List.of();
for (ResolveResult result : results) {
if (result.invocationSpec() != null) {
if (errors.isEmpty()) {
errors = List.of(result.invocationSpec());
} else if (errors.size() == 1) {... | errors.add(result.invocationSpec()); | private static List<SearchChainInvocationSpec> extractSpecs(List<ResolveResult> results) {
List<SearchChainInvocationSpec> errors = List.of();
for (ResolveResult result : results) {
if (result.invocationSpec() != null) {
if (errors.isEmpty()) {
errors = List.of(result.invocationSpec());
} else if (errors.size() == 1) {... | class SearchChaininvocationProxy extends SearchChainInvocationSpec {
SearchChaininvocationProxy(ComponentId searchChainId, FederationOptions federationOptions, String schema) {
super(searchChainId, federationOptions, List.of(schema));
}
@Override
public void modifyTargetQuery(Query query) {
query.getModel().setSources(... | class SearchChaininvocationProxy extends SearchChainInvocationSpec {
SearchChaininvocationProxy(ComponentId searchChainId, FederationOptions federationOptions, String schema) {
super(searchChainId, federationOptions, List.of(schema));
}
@Override
public void modifyTargetQuery(Query query) {
query.getModel().setSources(... |
done, please take another look | private String cloudAttr() {
if (zone == null) return "noCloud";
return zone.cloud().name().value();
} | } | private String cloudAttr() {
if (zone == null) return null;
return zone.cloud().name().value();
} | class OpenTelemetryConfigGenerator {
private final boolean useTls;
private final String ca_file;
private final String cert_file;
private final String key_file;
private List<StatePortInfo> statePorts = new ArrayList<>();
private final Zone zone;
private final ApplicationId applicationId;
OpenTelemetryConfigGenerator(Zon... | class OpenTelemetryConfigGenerator {
private final boolean useTls;
private final String ca_file;
private final String cert_file;
private final String key_file;
private List<StatePortInfo> statePorts = new ArrayList<>();
private final Zone zone;
private final ApplicationId applicationId;
OpenTelemetryConfigGenerator(Zon... |
Use the shared object mapper instance from `com.yahoo.json.Jackson.mapper()` instead. | public DefaultSignificanceModelRegistry(SignificanceConfig cfg) {
this.models = new EnumMap<>(Language.class);
ObjectMapper objectMapper = new ObjectMapper();
for (var model : cfg.model()) {
try {
SignificanceModelFile file = objectMapper.readValue(model.path().toFile(), SignificanceModelFile.class);
for (var pair : fi... | ObjectMapper objectMapper = new ObjectMapper(); | public DefaultSignificanceModelRegistry(SignificanceConfig cfg) {
this.models = new EnumMap<>(Language.class);
for (var model : cfg.model()) {
addModel(model.path());
}
} | class DefaultSignificanceModelRegistry implements SignificanceModelRegistry {
private final Map<Language, SignificanceModel> models;
@Inject
public DefaultSignificanceModelRegistry(List<Path> models) {
this.models = new EnumMap<>(Language.class);
ObjectMapper objectMapper = new ObjectMapper();
for (var model : models) ... | class DefaultSignificanceModelRegistry implements SignificanceModelRegistry {
private final Map<Language, SignificanceModel> models;
@Inject
public DefaultSignificanceModelRegistry(List<Path> models) {
this.models = new EnumMap<>(Language.class);
for (var path : models) {
addModel(path);
}
}
public void addModel(Path p... |
Wrap in the `IOException` in a `UncheckedIOException` | public DefaultSignificanceModelRegistry(SignificanceConfig cfg) {
this.models = new EnumMap<>(Language.class);
ObjectMapper objectMapper = new ObjectMapper();
for (var model : cfg.model()) {
try {
SignificanceModelFile file = objectMapper.readValue(model.path().toFile(), SignificanceModelFile.class);
for (var pair : fi... | throw new RuntimeException("Failed to load model from " + model.path(), e); | public DefaultSignificanceModelRegistry(SignificanceConfig cfg) {
this.models = new EnumMap<>(Language.class);
for (var model : cfg.model()) {
addModel(model.path());
}
} | class DefaultSignificanceModelRegistry implements SignificanceModelRegistry {
private final Map<Language, SignificanceModel> models;
@Inject
public DefaultSignificanceModelRegistry(List<Path> models) {
this.models = new EnumMap<>(Language.class);
ObjectMapper objectMapper = new ObjectMapper();
for (var model : models) ... | class DefaultSignificanceModelRegistry implements SignificanceModelRegistry {
private final Map<Language, SignificanceModel> models;
@Inject
public DefaultSignificanceModelRegistry(List<Path> models) {
this.models = new EnumMap<>(Language.class);
for (var path : models) {
addModel(path);
}
}
public void addModel(Path p... |
This code snippet is the same as in the other constructor and can be moved to a separate method to reduce code duplication. | public DefaultSignificanceModelRegistry(List<Path> models) {
this.models = new EnumMap<>(Language.class);
ObjectMapper objectMapper = new ObjectMapper();
for (var model : models) {
try {
SignificanceModelFile file = objectMapper.readValue(model.toFile(), SignificanceModelFile.class);
for (var pair : file.languages().en... | SignificanceModelFile file = objectMapper.readValue(model.toFile(), SignificanceModelFile.class); | public DefaultSignificanceModelRegistry(List<Path> models) {
this.models = new EnumMap<>(Language.class);
for (var path : models) {
addModel(path);
}
} | class DefaultSignificanceModelRegistry implements SignificanceModelRegistry {
private final Map<Language, SignificanceModel> models;
@Inject
public DefaultSignificanceModelRegistry(SignificanceConfig cfg) {
this.models = new EnumMap<>(Language.class);
ObjectMapper objectMapper = new ObjectMapper();
for (var model : cfg... | class DefaultSignificanceModelRegistry implements SignificanceModelRegistry {
private final Map<Language, SignificanceModel> models;
@Inject
public DefaultSignificanceModelRegistry(SignificanceConfig cfg) {
this.models = new EnumMap<>(Language.class);
for (var model : cfg.model()) {
addModel(model.path());
}
}
public v... |
Nvm, the `container-core` is not a dependency of `linguistics`. | public DefaultSignificanceModelRegistry(SignificanceConfig cfg) {
this.models = new EnumMap<>(Language.class);
ObjectMapper objectMapper = new ObjectMapper();
for (var model : cfg.model()) {
try {
SignificanceModelFile file = objectMapper.readValue(model.path().toFile(), SignificanceModelFile.class);
for (var pair : fi... | ObjectMapper objectMapper = new ObjectMapper(); | public DefaultSignificanceModelRegistry(SignificanceConfig cfg) {
this.models = new EnumMap<>(Language.class);
for (var model : cfg.model()) {
addModel(model.path());
}
} | class DefaultSignificanceModelRegistry implements SignificanceModelRegistry {
private final Map<Language, SignificanceModel> models;
@Inject
public DefaultSignificanceModelRegistry(List<Path> models) {
this.models = new EnumMap<>(Language.class);
ObjectMapper objectMapper = new ObjectMapper();
for (var model : models) ... | class DefaultSignificanceModelRegistry implements SignificanceModelRegistry {
private final Map<Language, SignificanceModel> models;
@Inject
public DefaultSignificanceModelRegistry(List<Path> models) {
this.models = new EnumMap<>(Language.class);
for (var path : models) {
addModel(path);
}
}
public void addModel(Path p... |
Maybe we should add the dimensions iff the value is not null? | private String cloudAttr() {
if (zone == null) return "noCloud";
return zone.cloud().name().value();
} | } | private String cloudAttr() {
if (zone == null) return null;
return zone.cloud().name().value();
} | class OpenTelemetryConfigGenerator {
private final boolean useTls;
private final String ca_file;
private final String cert_file;
private final String key_file;
private List<StatePortInfo> statePorts = new ArrayList<>();
private final Zone zone;
private final ApplicationId applicationId;
OpenTelemetryConfigGenerator(Zon... | class OpenTelemetryConfigGenerator {
private final boolean useTls;
private final String ca_file;
private final String cert_file;
private final String key_file;
private List<StatePortInfo> statePorts = new ArrayList<>();
private final Zone zone;
private final ApplicationId applicationId;
OpenTelemetryConfigGenerator(Zon... |
Why is this necessary? Do we serialize content of private fields? | public void generate() throws IOException {
Path currentWorkingDir = Paths.get("").toAbsolutePath();
final InputStream rawDoc = Files.newInputStream(currentWorkingDir.resolve(clientParameters.inputFile));
BufferedReader reader = new BufferedReader(new InputStreamReader(rawDoc));
long i = 1;
while (reader.ready()) {
Str... | objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); | public void generate() throws IOException {
Path currentWorkingDir = Paths.get("").toAbsolutePath();
final InputStream rawDoc = Files.newInputStream(currentWorkingDir.resolve(clientParameters.inputFile));
BufferedReader reader = new BufferedReader(new InputStreamReader(rawDoc));
long i = 1;
while (reader.ready()) {
Str... | class SignificanceModelGenerator {
private final ClientParameters clientParameters;
private final Tokenizer tokenizer;
private final HashMap<String, Long> documentFrequency = new HashMap<>();
private final Language language;
private final ObjectMapper objectMapper;
private final static JsonFactory parserFactory = new J... | class SignificanceModelGenerator {
private final ClientParameters clientParameters;
private final Tokenizer tokenizer;
private final HashMap<String, Long> documentFrequency = new HashMap<>();
private final Language language;
private final ObjectMapper objectMapper;
private final static JsonFactory parserFactory = new J... |
Add document type as a new CLI parameter instead of assuming it's named after the language. | public SignificanceModelGenerator(ClientParameters clientParameters) {
this.clientParameters = clientParameters;
OpenNlpLinguistics openNlpLinguistics = new OpenNlpLinguistics();
tokenizer = openNlpLinguistics.getTokenizer();
objectMapper = new ObjectMapper();
language = Language.fromLanguageTag(clientParameters.langua... | docType = new DocumentType(language.languageCode().toLowerCase()); | public SignificanceModelGenerator(ClientParameters clientParameters) {
this.clientParameters = clientParameters;
OpenNlpLinguistics openNlpLinguistics = new OpenNlpLinguistics();
tokenizer = openNlpLinguistics.getTokenizer();
objectMapper = new ObjectMapper();
language = Language.fromLanguageTag(clientParameters.langua... | class SignificanceModelGenerator {
private final ClientParameters clientParameters;
private final Tokenizer tokenizer;
private final HashMap<String, Long> documentFrequency = new HashMap<>();
private final Language language;
private final ObjectMapper objectMapper;
private final static JsonFactory parserFactory = new J... | class SignificanceModelGenerator {
private final ClientParameters clientParameters;
private final Tokenizer tokenizer;
private final HashMap<String, Long> documentFrequency = new HashMap<>();
private final Language language;
private final ObjectMapper objectMapper;
private final static JsonFactory parserFactory = new J... |
Good catch! Some leftover stuff again :D | public void generate() throws IOException {
Path currentWorkingDir = Paths.get("").toAbsolutePath();
final InputStream rawDoc = Files.newInputStream(currentWorkingDir.resolve(clientParameters.inputFile));
BufferedReader reader = new BufferedReader(new InputStreamReader(rawDoc));
long i = 1;
while (reader.ready()) {
Str... | objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); | public void generate() throws IOException {
Path currentWorkingDir = Paths.get("").toAbsolutePath();
final InputStream rawDoc = Files.newInputStream(currentWorkingDir.resolve(clientParameters.inputFile));
BufferedReader reader = new BufferedReader(new InputStreamReader(rawDoc));
long i = 1;
while (reader.ready()) {
Str... | class SignificanceModelGenerator {
private final ClientParameters clientParameters;
private final Tokenizer tokenizer;
private final HashMap<String, Long> documentFrequency = new HashMap<>();
private final Language language;
private final ObjectMapper objectMapper;
private final static JsonFactory parserFactory = new J... | class SignificanceModelGenerator {
private final ClientParameters clientParameters;
private final Tokenizer tokenizer;
private final HashMap<String, Long> documentFrequency = new HashMap<>();
private final Language language;
private final ObjectMapper objectMapper;
private final static JsonFactory parserFactory = new J... |
Added docType argument to cli ```java public static final String DOC_TYPE_OPTION = "doc-type"; options.addOption(Option.builder("d") .hasArg(true) .desc("Document type identifier") .longOpt(DOC_TYPE_OPTION) .build()); ``` | public SignificanceModelGenerator(ClientParameters clientParameters) {
this.clientParameters = clientParameters;
OpenNlpLinguistics openNlpLinguistics = new OpenNlpLinguistics();
tokenizer = openNlpLinguistics.getTokenizer();
objectMapper = new ObjectMapper();
language = Language.fromLanguageTag(clientParameters.langua... | docType = new DocumentType(language.languageCode().toLowerCase()); | public SignificanceModelGenerator(ClientParameters clientParameters) {
this.clientParameters = clientParameters;
OpenNlpLinguistics openNlpLinguistics = new OpenNlpLinguistics();
tokenizer = openNlpLinguistics.getTokenizer();
objectMapper = new ObjectMapper();
language = Language.fromLanguageTag(clientParameters.langua... | class SignificanceModelGenerator {
private final ClientParameters clientParameters;
private final Tokenizer tokenizer;
private final HashMap<String, Long> documentFrequency = new HashMap<>();
private final Language language;
private final ObjectMapper objectMapper;
private final static JsonFactory parserFactory = new J... | class SignificanceModelGenerator {
private final ClientParameters clientParameters;
private final Tokenizer tokenizer;
private final HashMap<String, Long> documentFrequency = new HashMap<>();
private final Language language;
private final ObjectMapper objectMapper;
private final static JsonFactory parserFactory = new J... |
Fail fast instead. | public Result search(Query query, Execution execution) {
var rankProfileName = query.getRanking().getProfile();
var schemas = schemaInfo.newSession(query).schemas();
var useSignficanceConfiguration = schemas.stream()
.map(schema -> schema.rankProfiles().get(rankProfileName))
.filter(Objects::nonNull)
.map(RankProfile::... | return execution.search(query); | public Result search(Query query, Execution execution) {
var rankProfileName = query.getRanking().getProfile();
var perSchemaSetup = schemaInfo.newSession(query).schemas().stream()
.collect(Collectors.toMap(Schema::name, schema ->
Optional.ofNullable(schema.rankProfiles().get(rankProfileName))
.map(RankProfile::useSign... | class SignificanceSearcher extends Searcher {
public final static String SIGNIFICANCE = "Significance";
private static final Logger log = Logger.getLogger(SignificanceSearcher.class.getName());
private final SignificanceModelRegistry significanceModelRegistry;
private final SchemaInfo schemaInfo;
@Inject
public Signifi... | class SignificanceSearcher extends Searcher {
public final static String SIGNIFICANCE = "Significance";
private static final Logger log = Logger.getLogger(SignificanceSearcher.class.getName());
private final SignificanceModelRegistry significanceModelRegistry;
private final SchemaInfo schemaInfo;
@Inject
public Signifi... |
See [bf6390b](https://github.com/vespa-engine/vespa/pull/31117/commits/bf6390b8dff4d1a5569e531ec68da8cd33b7ad73) | public Result search(Query query, Execution execution) {
var rankProfileName = query.getRanking().getProfile();
var schemas = schemaInfo.newSession(query).schemas();
var useSignficanceConfiguration = schemas.stream()
.map(schema -> schema.rankProfiles().get(rankProfileName))
.filter(Objects::nonNull)
.map(RankProfile::... | return execution.search(query); | public Result search(Query query, Execution execution) {
var rankProfileName = query.getRanking().getProfile();
var perSchemaSetup = schemaInfo.newSession(query).schemas().stream()
.collect(Collectors.toMap(Schema::name, schema ->
Optional.ofNullable(schema.rankProfiles().get(rankProfileName))
.map(RankProfile::useSign... | class SignificanceSearcher extends Searcher {
public final static String SIGNIFICANCE = "Significance";
private static final Logger log = Logger.getLogger(SignificanceSearcher.class.getName());
private final SignificanceModelRegistry significanceModelRegistry;
private final SchemaInfo schemaInfo;
@Inject
public Signifi... | class SignificanceSearcher extends Searcher {
public final static String SIGNIFICANCE = "Significance";
private static final Logger log = Logger.getLogger(SignificanceSearcher.class.getName());
private final SignificanceModelRegistry significanceModelRegistry;
private final SchemaInfo schemaInfo;
@Inject
public Signifi... |
~It wasn't originally, but it certainly makes sense, I'll try to do that~ I'll look into this in another PR | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
try {
java.nio.file.Path tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.move(tempDir, prep... | preprocessedApp.copyUserDefsIntoApplication(); | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
try {
java.nio.file.Path tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.move(tempDir, prep... | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} |
Consider returning false from `space.valid()` unless `0 <= getBucketsPending() <= getBucketsTotal()`, or squeeze getBucketsPending() in `[0, getBucketsTotlal()]` ? | public static Optional<Double> clusterBucketsOutOfSyncRatio(ContentNodeStats globalStats) {
long totalBuckets = 0;
long pendingBuckets = 0;
for (var space : globalStats.getBucketSpaces().values()) {
if (!space.valid()) {
return Optional.empty();
}
totalBuckets += space.getBucketsTotal();
pendingBuckets += space.getBu... | pendingBuckets = Math.min(pendingBuckets, totalBuckets); | public static Optional<Double> clusterBucketsOutOfSyncRatio(ContentNodeStats globalStats) {
long totalBuckets = 0;
long pendingBuckets = 0;
for (var space : globalStats.getBucketSpaces().values()) {
if (!space.valid()) {
return Optional.empty();
}
totalBuckets += space.getBucketsTotal();
pendingBuckets += space.getBu... | class GlobalBucketSyncStatsCalculator {
/**
* Compute a value in [0, 1] representing how much of the cluster's data space is currently
* out of sync, i.e. pending merging. In other words, if the value is 1 all buckets are out
* of sync, and conversely if it's 0 all buckets are in sync. This number applies across bucket... | class GlobalBucketSyncStatsCalculator {
/**
* Compute a value in [0, 1] representing how much of the cluster's data space is currently
* out of sync, i.e. pending merging. In other words, if the value is 1 all buckets are out
* of sync, and conversely if it's 0 all buckets are in sync. This number applies across bucket... |
This one is a bit tricky... It's currently possible for the reported number of pending buckets to be greater than the number of total buckets. Example: this can happen if a bucket is present on a single node, but should have been replicated to 9 more nodes. Since reported counts are not currently normalized _across_ c... | public static Optional<Double> clusterBucketsOutOfSyncRatio(ContentNodeStats globalStats) {
long totalBuckets = 0;
long pendingBuckets = 0;
for (var space : globalStats.getBucketSpaces().values()) {
if (!space.valid()) {
return Optional.empty();
}
totalBuckets += space.getBucketsTotal();
pendingBuckets += space.getBu... | pendingBuckets = Math.min(pendingBuckets, totalBuckets); | public static Optional<Double> clusterBucketsOutOfSyncRatio(ContentNodeStats globalStats) {
long totalBuckets = 0;
long pendingBuckets = 0;
for (var space : globalStats.getBucketSpaces().values()) {
if (!space.valid()) {
return Optional.empty();
}
totalBuckets += space.getBucketsTotal();
pendingBuckets += space.getBu... | class GlobalBucketSyncStatsCalculator {
/**
* Compute a value in [0, 1] representing how much of the cluster's data space is currently
* out of sync, i.e. pending merging. In other words, if the value is 1 all buckets are out
* of sync, and conversely if it's 0 all buckets are in sync. This number applies across bucket... | class GlobalBucketSyncStatsCalculator {
/**
* Compute a value in [0, 1] representing how much of the cluster's data space is currently
* out of sync, i.e. pending merging. In other words, if the value is 1 all buckets are out
* of sync, and conversely if it's 0 all buckets are in sync. This number applies across bucket... |
:+1: | public static Optional<Double> clusterBucketsOutOfSyncRatio(ContentNodeStats globalStats) {
long totalBuckets = 0;
long pendingBuckets = 0;
for (var space : globalStats.getBucketSpaces().values()) {
if (!space.valid()) {
return Optional.empty();
}
totalBuckets += space.getBucketsTotal();
pendingBuckets += space.getBu... | pendingBuckets = Math.min(pendingBuckets, totalBuckets); | public static Optional<Double> clusterBucketsOutOfSyncRatio(ContentNodeStats globalStats) {
long totalBuckets = 0;
long pendingBuckets = 0;
for (var space : globalStats.getBucketSpaces().values()) {
if (!space.valid()) {
return Optional.empty();
}
totalBuckets += space.getBucketsTotal();
pendingBuckets += space.getBu... | class GlobalBucketSyncStatsCalculator {
/**
* Compute a value in [0, 1] representing how much of the cluster's data space is currently
* out of sync, i.e. pending merging. In other words, if the value is 1 all buckets are out
* of sync, and conversely if it's 0 all buckets are in sync. This number applies across bucket... | class GlobalBucketSyncStatsCalculator {
/**
* Compute a value in [0, 1] representing how much of the cluster's data space is currently
* out of sync, i.e. pending merging. In other words, if the value is 1 all buckets are out
* of sync, and conversely if it's 0 all buckets are in sync. This number applies across bucket... |
Should there be a precondition check here that `clusterName` is actually contained in `referents`? Otherwise the entry will be implicitly created with a refcount of `-1`. If the cluster is then subsequently registered, it will be merged as `-1 + 1`, ending up with a refcount of 0 for a live entry, which may have exciti... | void countdown(String clusterName) {
synchronized (monitor) {
if (0 == referents.merge(clusterName, -1, Integer::sum)) {
shutDownController(controllers.remove(clusterName));
status.remove(clusterName);
}
}
} | if (0 == referents.merge(clusterName, -1, Integer::sum)) { | void countdown(String clusterName) {
synchronized (monitor) {
referents.compute(clusterName, (__, count) -> {
if (count == null) throw new IllegalStateException("trying to remove unknown cluster: " + clusterName);
if (count == 1) {
shutDownController(controllers.remove(clusterName));
status.remove(clusterName);
return ... | class ClusterController extends AbstractComponent
implements ClusterControllerStateRestAPI.FleetControllerResolver,
StatusHandler.ClusterStatusPageServerSet {
private static final Logger log = Logger.getLogger(ClusterController.class.getName());
private final JDiscMetricWrapper metricWrapper;
private final Object monit... | class ClusterController extends AbstractComponent
implements ClusterControllerStateRestAPI.FleetControllerResolver,
StatusHandler.ClusterStatusPageServerSet {
private static final Logger log = Logger.getLogger(ClusterController.class.getName());
private final JDiscMetricWrapper metricWrapper;
private final Object monit... |
Conflicting with the static subclass `Collectors` that I introduced | private InvalidJsonException createInvalidTypeException(Type... expected) {
var expectedTypesString = Arrays.stream(expected).map(this::toString)
.collect(java.util.stream.Collectors.joining("' or '", "'", "'"));
var pathString = path.isEmpty() ? "JSON" : "JSON member '%s'".formatted(path);
return new InvalidJsonExcept... | .collect(java.util.stream.Collectors.joining("' or '", "'", "'")); | private InvalidJsonException createInvalidTypeException(Type... expected) {
var expectedTypesString = Arrays.stream(expected).map(this::toString)
.collect(java.util.stream.Collectors.joining("' or '", "'", "'"));
var pathString = path.isEmpty() ? "JSON" : "JSON member '%s'".formatted(path);
return new InvalidJsonExcept... | class Json implements Iterable<Json> {
private final Inspector inspector;
private final String path;
public static Json of(Slime slime) { return of(slime.get()); }
public static Json of(Inspector inspector) { return new Json(inspector, ""); }
public static Json of(String json) { return of(SlimeUtils.jsonToSlime(json));... | class Json implements Iterable<Json> {
private final Inspector inspector;
private final String path;
public static Json of(Slime slime) { return of(slime.get()); }
public static Json of(Inspector inspector) { return new Json(inspector, ""); }
public static Json of(String json) { return of(SlimeUtils.jsonToSlime(json));... |
That shouldn't be possible, and I think we'd have bigger problems already if it were to happen, but I guess being explicit about this doesn't hurt much either. | void countdown(String clusterName) {
synchronized (monitor) {
if (0 == referents.merge(clusterName, -1, Integer::sum)) {
shutDownController(controllers.remove(clusterName));
status.remove(clusterName);
}
}
} | if (0 == referents.merge(clusterName, -1, Integer::sum)) { | void countdown(String clusterName) {
synchronized (monitor) {
referents.compute(clusterName, (__, count) -> {
if (count == null) throw new IllegalStateException("trying to remove unknown cluster: " + clusterName);
if (count == 1) {
shutDownController(controllers.remove(clusterName));
status.remove(clusterName);
return ... | class ClusterController extends AbstractComponent
implements ClusterControllerStateRestAPI.FleetControllerResolver,
StatusHandler.ClusterStatusPageServerSet {
private static final Logger log = Logger.getLogger(ClusterController.class.getName());
private final JDiscMetricWrapper metricWrapper;
private final Object monit... | class ClusterController extends AbstractComponent
implements ClusterControllerStateRestAPI.FleetControllerResolver,
StatusHandler.ClusterStatusPageServerSet {
private static final Logger log = Logger.getLogger(ClusterController.class.getName());
private final JDiscMetricWrapper metricWrapper;
private final Object monit... |
Leftover from debugging.... Keep or remove ? | void testConnectivity() {
QueryTree parsed = parse("select foo from bar where " +
"title contains ({id: 1, connectivity: {\"id\": 3, weight: 7.0}}\"madonna\") " +
"and title contains ({id: 2}\"saint\") " +
"and title contains ({id: 3}\"angel\")");
assertEquals("AND title:madonna title:saint title:angel", parsed.toStrin... | System.out.println(new TextualQueryRepresentation(root)); | void testConnectivity() {
QueryTree parsed = parse("select foo from bar where " +
"title contains ({id: 1, connectivity: {\"id\": 3, weight: 7.0}}\"madonna\") " +
"and title contains ({id: 2}\"saint\") " +
"and title contains ({id: 3}\"angel\")");
assertEquals("AND title:madonna title:saint title:angel", parsed.toStrin... | class YqlParserTestCase {
private YqlParser parser;
@BeforeEach
public void setUp() throws Exception {
ParserEnvironment env = new ParserEnvironment();
parser = new YqlParser(env);
}
@AfterEach
public void tearDown() throws Exception {
parser = null;
}
static private IndexFacts createIndexFactsForInTest() {
SearchDefin... | class YqlParserTestCase {
private YqlParser parser;
@BeforeEach
public void setUp() throws Exception {
ParserEnvironment env = new ParserEnvironment();
parser = new YqlParser(env);
}
@AfterEach
public void tearDown() throws Exception {
parser = null;
}
static private IndexFacts createIndexFactsForInTest() {
SearchDefin... |
```suggestion ``` | void testConnectivity() {
QueryTree parsed = parse("select foo from bar where " +
"title contains ({id: 1, connectivity: {\"id\": 3, weight: 7.0}}\"madonna\") " +
"and title contains ({id: 2}\"saint\") " +
"and title contains ({id: 3}\"angel\")");
assertEquals("AND title:madonna title:saint title:angel", parsed.toStrin... | System.out.println(new TextualQueryRepresentation(root)); | void testConnectivity() {
QueryTree parsed = parse("select foo from bar where " +
"title contains ({id: 1, connectivity: {\"id\": 3, weight: 7.0}}\"madonna\") " +
"and title contains ({id: 2}\"saint\") " +
"and title contains ({id: 3}\"angel\")");
assertEquals("AND title:madonna title:saint title:angel", parsed.toStrin... | class YqlParserTestCase {
private YqlParser parser;
@BeforeEach
public void setUp() throws Exception {
ParserEnvironment env = new ParserEnvironment();
parser = new YqlParser(env);
}
@AfterEach
public void tearDown() throws Exception {
parser = null;
}
static private IndexFacts createIndexFactsForInTest() {
SearchDefin... | class YqlParserTestCase {
private YqlParser parser;
@BeforeEach
public void setUp() throws Exception {
ParserEnvironment env = new ParserEnvironment();
parser = new YqlParser(env);
}
@AfterEach
public void tearDown() throws Exception {
parser = null;
}
static private IndexFacts createIndexFactsForInTest() {
SearchDefin... |
The returned value has the format project/instancename - so return a record with those fields? | public static Optional<String> getInstanceName(List<SubjectAlternativeName> sans) {
return getLastSegmentFromSanUri(sans, "athenz:
} | return getLastSegmentFromSanUri(sans, "athenz: | public static Optional<String> getInstanceName(List<SubjectAlternativeName> sans) {
return getLastSegmentFromSanUri(sans, "athenz:
} | class AthenzX509CertificateUtils {
private AthenzX509CertificateUtils() {}
public static AthenzIdentity getIdentityFromRoleCertificate(X509Certificate certificate) {
List<SubjectAlternativeName> sans = X509CertificateUtils.getSubjectAlternativeNames(certificate);
return getRoleIdentityFromEmail(sans)
.or(() -> getRoleI... | class AthenzX509CertificateUtils {
private AthenzX509CertificateUtils() {}
public static AthenzIdentity getIdentityFromRoleCertificate(X509Certificate certificate) {
List<SubjectAlternativeName> sans = X509CertificateUtils.getSubjectAlternativeNames(certificate);
return getRoleIdentityFromEmail(sans)
.or(() -> getRoleI... |
The returned value is only the instance name, since it returns the last path segment | public static Optional<String> getInstanceName(List<SubjectAlternativeName> sans) {
return getLastSegmentFromSanUri(sans, "athenz:
} | return getLastSegmentFromSanUri(sans, "athenz: | public static Optional<String> getInstanceName(List<SubjectAlternativeName> sans) {
return getLastSegmentFromSanUri(sans, "athenz:
} | class AthenzX509CertificateUtils {
private AthenzX509CertificateUtils() {}
public static AthenzIdentity getIdentityFromRoleCertificate(X509Certificate certificate) {
List<SubjectAlternativeName> sans = X509CertificateUtils.getSubjectAlternativeNames(certificate);
return getRoleIdentityFromEmail(sans)
.or(() -> getRoleI... | class AthenzX509CertificateUtils {
private AthenzX509CertificateUtils() {}
public static AthenzIdentity getIdentityFromRoleCertificate(X509Certificate certificate) {
List<SubjectAlternativeName> sans = X509CertificateUtils.getSubjectAlternativeNames(certificate);
return getRoleIdentityFromEmail(sans)
.or(() -> getRoleI... |
Consider using nano time to more accurately measure elapsed time (that is not affected by wall clock adjustments etc). | public Duration timeLeft() {
return Duration.ofMillis(deadlineMillis - clock.getAsLong());
} | return Duration.ofMillis(deadlineMillis - clock.getAsLong()); | public Duration timeLeft() {
return Duration.ofNanos(deadlineNanos - nanoClock.getAsLong());
} | class HttpRequest {
private final String method;
private final String path;
private final Map<String, Supplier<String>> headers;
private final byte[] body;
private final long deadlineMillis;
private final LongSupplier clock;
public HttpRequest(String method, String path, Map<String, Supplier<String>> headers, byte[] bo... | class HttpRequest {
private final String method;
private final String path;
private final Map<String, Supplier<String>> headers;
private final byte[] body;
private final Duration timeout;
private final long deadlineNanos;
private final LongSupplier nanoClock;
public HttpRequest(String method, String path, Map<String, S... |
```suggestion "last " + failingNanos / 1_000_000 + "ms. The server will be pinged to see if it recovers" + (doomNanos >= 0 ? ", but this client will give up if no successes are observed within " + doomNanos / 1_000_000 + "ms" : "") + ``` | public State state() {
long failingNanos = nanoClock.getAsLong() - failingSinceNanos.get();
if (failingNanos > graceNanos && halfOpen.compareAndSet(false, true))
log.log(INFO, "Circuit breaker is now half-open, as no requests have succeeded for the " +
"last " + failingNanos / 1000 + "ms. The server will be pinged to s... | (doomNanos >= 0 ? ", but this client will give up if no successes are observed within " + doomNanos / 1000 + "ms" : "") + | public State state() {
long failingNanos = nanoClock.getAsLong() - failingSinceNanos.get();
if (failingNanos > graceNanos && halfOpen.compareAndSet(false, true))
log.log(INFO, "Circuit breaker is now half-open, as no requests have succeeded for the " +
"last " + failingNanos / 1_000_000 + "ms. The server will be pinged... | class GracePeriodCircuitBreaker implements FeedClient.CircuitBreaker {
private static final Logger log = Logger.getLogger(GracePeriodCircuitBreaker.class.getName());
private final AtomicBoolean halfOpen = new AtomicBoolean(false);
private final AtomicBoolean open = new AtomicBoolean(false);
private final LongSupplier n... | class GracePeriodCircuitBreaker implements FeedClient.CircuitBreaker {
private static final Logger log = Logger.getLogger(GracePeriodCircuitBreaker.class.getName());
private final AtomicBoolean halfOpen = new AtomicBoolean(false);
private final AtomicBoolean open = new AtomicBoolean(false);
private final LongSupplier n... |
```suggestion log.log(WARNING, "Circuit breaker is now open, after " + doomNanos / 1_000_000 + "ms of failing request, " + ``` | public State state() {
long failingNanos = nanoClock.getAsLong() - failingSinceNanos.get();
if (failingNanos > graceNanos && halfOpen.compareAndSet(false, true))
log.log(INFO, "Circuit breaker is now half-open, as no requests have succeeded for the " +
"last " + failingNanos / 1000 + "ms. The server will be pinged to s... | log.log(WARNING, "Circuit breaker is now open, after " + doomNanos / 1000 + "ms of failing request, " + | public State state() {
long failingNanos = nanoClock.getAsLong() - failingSinceNanos.get();
if (failingNanos > graceNanos && halfOpen.compareAndSet(false, true))
log.log(INFO, "Circuit breaker is now half-open, as no requests have succeeded for the " +
"last " + failingNanos / 1_000_000 + "ms. The server will be pinged... | class GracePeriodCircuitBreaker implements FeedClient.CircuitBreaker {
private static final Logger log = Logger.getLogger(GracePeriodCircuitBreaker.class.getName());
private final AtomicBoolean halfOpen = new AtomicBoolean(false);
private final AtomicBoolean open = new AtomicBoolean(false);
private final LongSupplier n... | class GracePeriodCircuitBreaker implements FeedClient.CircuitBreaker {
private static final Logger log = Logger.getLogger(GracePeriodCircuitBreaker.class.getName());
private final AtomicBoolean halfOpen = new AtomicBoolean(false);
private final AtomicBoolean open = new AtomicBoolean(false);
private final LongSupplier n... |
`inflight` will hold a reference to all previous and current operations until a reset occur? So it will leak memory until the circuit breaker is tripped? | public void dispatch(HttpRequest request, CompletableFuture<HttpResponse> vessel) {
inflight.add(vessel);
delegate.dispatch(request, vessel);
} | inflight.add(vessel); | public void dispatch(HttpRequest request, CompletableFuture<HttpResponse> vessel) {
synchronized (monitor) {
AtomicLong usedCounter = inflight;
Cluster usedCluster = delegate;
usedCounter.incrementAndGet();
delegate.dispatch(request, vessel);
vessel.whenComplete((__, ___) -> {
synchronized (monitor) {
if (usedCounter.d... | class ResettableCluster implements Cluster {
private final Object monitor = new Object();
private final Deque<CompletableFuture<?>> inflight = new ArrayDeque<>();
private final Supplier<Cluster> delegates;
private Cluster delegate;
ResettableCluster(Supplier<Cluster> delegates) {
this.delegates = delegates;
this.delega... | class ResettableCluster implements Cluster {
private final Object monitor = new Object();
private final ClusterFactory clusterFactory;
private AtomicLong inflight = new AtomicLong(0);
private Cluster delegate;
ResettableCluster(ClusterFactory clusterFactory) throws IOException {
this.clusterFactory = clusterFactory;
th... |
Hmm, should probably check for children among `potentialChildren`, only. | static void validateParentHosts(ApplicationId application, NodeList allNodes, NodeList potentialChildren) {
Set<String> parentHostnames = potentialChildren.stream()
.map(Node::parentHostname)
.flatMap(Optional::stream)
.collect(Collectors.toSet());
Set<String> nonActiveHosts = allNodes.not().state(Node.State.active)
.m... | applicationParentHostnames.removeIf(host -> allNodes.childrenOf(host).type(Type.combined, Type.container, Type.content).isEmpty()); | static void validateParentHosts(ApplicationId application, NodeList allNodes, NodeList potentialChildren) {
Set<String> parentHostnames = potentialChildren.stream()
.map(Node::parentHostname)
.flatMap(Optional::stream)
.collect(Collectors.toSet());
Set<String> nonActiveHosts = allNodes.not().state(Node.State.active)
.m... | class Activator {
private final NodeRepository nodeRepository;
private final Optional<LoadBalancerProvisioner> loadBalancerProvisioner;
public Activator(NodeRepository nodeRepository, Optional<LoadBalancerProvisioner> loadBalancerProvisioner) {
this.nodeRepository = nodeRepository;
this.loadBalancerProvisioner = loadBa... | class Activator {
private final NodeRepository nodeRepository;
private final Optional<LoadBalancerProvisioner> loadBalancerProvisioner;
public Activator(NodeRepository nodeRepository, Optional<LoadBalancerProvisioner> loadBalancerProvisioner) {
this.nodeRepository = nodeRepository;
this.loadBalancerProvisioner = loadBa... |
This is only used in the JvmHeapSizeValidator, which used to compare this number against 15%. If that comparison also should be against the fixed percentage (of available, not of total), which is a loose bound than this, then this number can be omitted from the `JvmMemoryPercentage`. | public Optional<JvmMemoryPercentage> getMemoryPercentage() {
if (memoryPercentage != null) return Optional.of(JvmMemoryPercentage.of(memoryPercentage));
if (isHostedVespa()) {
int heapSizePercentageOfAvailable = heapSizePercentageOfAvailable();
if (getContainers().isEmpty()) return Optional.of(JvmMemoryPercentage.of(he... | int memoryPercentageOfTotal = (int) (heapSizePercentageOfAvailable * availableMemoryGb / totalMemoryGb); | public Optional<JvmMemoryPercentage> getMemoryPercentage() {
if (memoryPercentage != null) return Optional.of(JvmMemoryPercentage.of(memoryPercentage));
if (isHostedVespa()) {
int heapSizePercentageOfAvailable = heapSizePercentageOfAvailable();
if (getContainers().isEmpty()) return Optional.of(JvmMemoryPercentage.of(he... | class ApplicationContainerCluster extends ContainerCluster<ApplicationContainer> implements
ApplicationBundlesConfig.Producer,
QrStartConfig.Producer,
RankProfilesConfig.Producer,
RankingConstantsConfig.Producer,
OnnxModelsConfig.Producer,
RankingExpressionsConfig.Producer,
ContainerMbusConfig.Producer,
MetricsProxyApi... | class ApplicationContainerCluster extends ContainerCluster<ApplicationContainer> implements
ApplicationBundlesConfig.Producer,
QrStartConfig.Producer,
RankProfilesConfig.Producer,
RankingConstantsConfig.Producer,
OnnxModelsConfig.Producer,
RankingExpressionsConfig.Producer,
ContainerMbusConfig.Producer,
MetricsProxyApi... |
FYI typo introduced from structured renaming | public Optional<JvmMemoryPercentage> getMemoryPercentage() {
if (memoryPercentage != null) return Optional.of(JvmMemoryPercentage.of(memoryPercentage));
if (isHostedVespa()) {
int heapSizePercentageOfAvailable = heapSizePercentageOfAvailable();
if (getContainers().isEmpty()) return Optional.of(JvmMemoryPercentage.of(he... | public Optional<JvmMemoryPercentage> getMemoryPercentage() {
if (memoryPercentage != null) return Optional.of(JvmMemoryPercentage.of(memoryPercentage));
if (isHostedVespa()) {
int heapSizePercentageOfAvailable = heapSizePercentageOfAvailable();
if (getContainers().isEmpty()) return Optional.of(JvmMemoryPercentage.of(he... | class ApplicationContainerCluster extends ContainerCluster<ApplicationContainer> implements
ApplicationBundlesConfig.Producer,
QrStartConfig.Producer,
RankProfilesConfig.Producer,
RankingConstantsConfig.Producer,
OnnxModelsConfig.Producer,
RankingExpressionsConfig.Producer,
ContainerMbusConfig.Producer,
MetricsProxyApi... | class ApplicationContainerCluster extends ContainerCluster<ApplicationContainer> implements
ApplicationBundlesConfig.Producer,
QrStartConfig.Producer,
RankProfilesConfig.Producer,
RankingConstantsConfig.Producer,
OnnxModelsConfig.Producer,
RankingExpressionsConfig.Producer,
ContainerMbusConfig.Producer,
MetricsProxyApi... | |
_This_ is what the startup scripts actually need. | public Optional<JvmMemoryPercentage> getMemoryPercentage() {
if (memoryPercentage != null) return Optional.of(JvmMemoryPercentage.of(memoryPercentage));
if (isHostedVespa()) {
int heapSizePercentageOfAvailable = heapSizePercentageOfAvailable();
if (getContainers().isEmpty()) return Optional.of(JvmMemoryPercentage.of(he... | int memoryPercentageOfAvailable = (int) (heapSizePercentageOfAvailable * availableMemoryGb / totalMemoryMinusOverhead); | public Optional<JvmMemoryPercentage> getMemoryPercentage() {
if (memoryPercentage != null) return Optional.of(JvmMemoryPercentage.of(memoryPercentage));
if (isHostedVespa()) {
int heapSizePercentageOfAvailable = heapSizePercentageOfAvailable();
if (getContainers().isEmpty()) return Optional.of(JvmMemoryPercentage.of(he... | class ApplicationContainerCluster extends ContainerCluster<ApplicationContainer> implements
ApplicationBundlesConfig.Producer,
QrStartConfig.Producer,
RankProfilesConfig.Producer,
RankingConstantsConfig.Producer,
OnnxModelsConfig.Producer,
RankingExpressionsConfig.Producer,
ContainerMbusConfig.Producer,
MetricsProxyApi... | class ApplicationContainerCluster extends ContainerCluster<ApplicationContainer> implements
ApplicationBundlesConfig.Producer,
QrStartConfig.Producer,
RankProfilesConfig.Producer,
RankingConstantsConfig.Producer,
OnnxModelsConfig.Producer,
RankingExpressionsConfig.Producer,
ContainerMbusConfig.Producer,
MetricsProxyApi... |
No success is already logged at info level at line 102. I would just make this a warning right away as that stands out more and is easier to detect. | protected double maintain() {
int attempts = 0;
int[] failures = new int[1];
List<Runnable> futureDownloads = new ArrayList<>();
for (TenantName tenantName : applicationRepository.tenantRepository().getAllTenantNames()) {
for (Session session : applicationRepository.tenantRepository().getTenant(tenantName).getSessionRe... | log.info("Exception when downloading application package (" + appFileReference + ")" + | protected double maintain() {
int attempts = 0;
int[] failures = new int[1];
List<Runnable> futureDownloads = new ArrayList<>();
for (TenantName tenantName : applicationRepository.tenantRepository().getAllTenantNames()) {
for (Session session : applicationRepository.tenantRepository().getTenant(tenantName).getSessionRe... | class ApplicationPackageMaintainer extends ConfigServerMaintainer {
private static final Logger log = Logger.getLogger(ApplicationPackageMaintainer.class.getName());
private final File downloadDirectory;
private final Supervisor supervisor = new Supervisor(new Transport("filedistribution-pool")).setDropEmptyBuffers(tru... | class ApplicationPackageMaintainer extends ConfigServerMaintainer {
private static final Logger log = Logger.getLogger(ApplicationPackageMaintainer.class.getName());
private final File downloadDirectory;
private final Supervisor supervisor = new Supervisor(new Transport("filedistribution-pool")).setDropEmptyBuffers(tru... |
Makes sense, done, need a new review | protected double maintain() {
int attempts = 0;
int[] failures = new int[1];
List<Runnable> futureDownloads = new ArrayList<>();
for (TenantName tenantName : applicationRepository.tenantRepository().getAllTenantNames()) {
for (Session session : applicationRepository.tenantRepository().getTenant(tenantName).getSessionRe... | log.info("Exception when downloading application package (" + appFileReference + ")" + | protected double maintain() {
int attempts = 0;
int[] failures = new int[1];
List<Runnable> futureDownloads = new ArrayList<>();
for (TenantName tenantName : applicationRepository.tenantRepository().getAllTenantNames()) {
for (Session session : applicationRepository.tenantRepository().getTenant(tenantName).getSessionRe... | class ApplicationPackageMaintainer extends ConfigServerMaintainer {
private static final Logger log = Logger.getLogger(ApplicationPackageMaintainer.class.getName());
private final File downloadDirectory;
private final Supervisor supervisor = new Supervisor(new Transport("filedistribution-pool")).setDropEmptyBuffers(tru... | class ApplicationPackageMaintainer extends ConfigServerMaintainer {
private static final Logger log = Logger.getLogger(ApplicationPackageMaintainer.class.getName());
private final File downloadDirectory;
private final Supervisor supervisor = new Supervisor(new Transport("filedistribution-pool")).setDropEmptyBuffers(tru... |
Should be `"^.*:[01](\\.\\d+)?$"`, i.e., without the `|` in the character set. | private HostedSslConnectorFactory(Builder builder) {
super(new ConnectorFactory.Builder("tls"+builder.port, builder.port).sslProvider(createSslProvider(builder)));
this.clientAuth = builder.clientAuth;
this.tlsCiphersOverride = List.copyOf(builder.tlsCiphersOverride);
this.proxyProtocolEnabled = builder.proxyProtocolEn... | var regex = "^.*:[0|1](\\.\\d+)?$"; | private HostedSslConnectorFactory(Builder builder) {
super(new ConnectorFactory.Builder("tls"+builder.port, builder.port).sslProvider(createSslProvider(builder)));
this.clientAuth = builder.clientAuth;
this.tlsCiphersOverride = List.copyOf(builder.tlsCiphersOverride);
this.proxyProtocolEnabled = builder.proxyProtocolEn... | class HostedSslConnectorFactory extends ConnectorFactory {
private final SslClientAuth clientAuth;
private final List<String> tlsCiphersOverride;
private final boolean proxyProtocolEnabled;
private final Duration endpointConnectionTtl;
private final List<String> remoteAddressHeaders;
private final List<String> remotePo... | class HostedSslConnectorFactory extends ConnectorFactory {
private final SslClientAuth clientAuth;
private final List<String> tlsCiphersOverride;
private final boolean proxyProtocolEnabled;
private final Duration endpointConnectionTtl;
private final List<String> remoteAddressHeaders;
private final List<String> remotePo... |
Should this also be inside the atomic move? | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
try {
java.nio.file.Path tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.move(tempDir, prep... | preprocessedApp.copyUserDefsIntoApplication(); | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
try {
java.nio.file.Path tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.move(tempDir, prep... | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} |
```suggestion var regex = "^.*:[01](\\.\\d+)?:\\d+[a-zA-Z]+$"; ``` This should be changed the other place too, from the previous PR! | private HostedSslConnectorFactory(Builder builder) {
super(new ConnectorFactory.Builder("tls"+builder.port, builder.port).sslProvider(createSslProvider(builder)));
this.clientAuth = builder.clientAuth;
this.tlsCiphersOverride = List.copyOf(builder.tlsCiphersOverride);
this.proxyProtocolEnabled = builder.proxyProtocolEn... | var regex = "^.*:[0|1](\\.\\d+)?:\\d+[a-zA-Z]+$"; | private HostedSslConnectorFactory(Builder builder) {
super(new ConnectorFactory.Builder("tls"+builder.port, builder.port).sslProvider(createSslProvider(builder)));
this.clientAuth = builder.clientAuth;
this.tlsCiphersOverride = List.copyOf(builder.tlsCiphersOverride);
this.proxyProtocolEnabled = builder.proxyProtocolEn... | class HostedSslConnectorFactory extends ConnectorFactory {
private final SslClientAuth clientAuth;
private final List<String> tlsCiphersOverride;
private final boolean proxyProtocolEnabled;
private final Duration endpointConnectionTtl;
private final List<String> remoteAddressHeaders;
private final List<String> remotePo... | class HostedSslConnectorFactory extends ConnectorFactory {
private record EntityLoggingEntry(String prefix, double sampleRate, BytesQuantity maxEntitySize) {}
private final SslClientAuth clientAuth;
private final List<String> tlsCiphersOverride;
private final boolean proxyProtocolEnabled;
private final Duration endpoin... |
To ensure there are exactly _three_ parts, as expected in later code, perhaps also replace the leading `.*` with `[^:]*`. | private HostedSslConnectorFactory(Builder builder) {
super(new ConnectorFactory.Builder("tls"+builder.port, builder.port).sslProvider(createSslProvider(builder)));
this.clientAuth = builder.clientAuth;
this.tlsCiphersOverride = List.copyOf(builder.tlsCiphersOverride);
this.proxyProtocolEnabled = builder.proxyProtocolEn... | var regex = "^.*:[0|1](\\.\\d+)?:\\d+[a-zA-Z]+$"; | private HostedSslConnectorFactory(Builder builder) {
super(new ConnectorFactory.Builder("tls"+builder.port, builder.port).sslProvider(createSslProvider(builder)));
this.clientAuth = builder.clientAuth;
this.tlsCiphersOverride = List.copyOf(builder.tlsCiphersOverride);
this.proxyProtocolEnabled = builder.proxyProtocolEn... | class HostedSslConnectorFactory extends ConnectorFactory {
private final SslClientAuth clientAuth;
private final List<String> tlsCiphersOverride;
private final boolean proxyProtocolEnabled;
private final Duration endpointConnectionTtl;
private final List<String> remoteAddressHeaders;
private final List<String> remotePo... | class HostedSslConnectorFactory extends ConnectorFactory {
private record EntityLoggingEntry(String prefix, double sampleRate, BytesQuantity maxEntitySize) {}
private final SslClientAuth clientAuth;
private final List<String> tlsCiphersOverride;
private final boolean proxyProtocolEnabled;
private final Duration endpoin... |
So ... this may fail during preparation, but is set in a feature flag? I think the flag should also enforce the pattern, then. Does it? | private HostedSslConnectorFactory(Builder builder) {
super(new ConnectorFactory.Builder("tls"+builder.port, builder.port).sslProvider(createSslProvider(builder)));
this.clientAuth = builder.clientAuth;
this.tlsCiphersOverride = List.copyOf(builder.tlsCiphersOverride);
this.proxyProtocolEnabled = builder.proxyProtocolEn... | var regex = "^.*:[0|1](\\.\\d+)?:\\d+[a-zA-Z]+$"; | private HostedSslConnectorFactory(Builder builder) {
super(new ConnectorFactory.Builder("tls"+builder.port, builder.port).sslProvider(createSslProvider(builder)));
this.clientAuth = builder.clientAuth;
this.tlsCiphersOverride = List.copyOf(builder.tlsCiphersOverride);
this.proxyProtocolEnabled = builder.proxyProtocolEn... | class HostedSslConnectorFactory extends ConnectorFactory {
private final SslClientAuth clientAuth;
private final List<String> tlsCiphersOverride;
private final boolean proxyProtocolEnabled;
private final Duration endpointConnectionTtl;
private final List<String> remoteAddressHeaders;
private final List<String> remotePo... | class HostedSslConnectorFactory extends ConnectorFactory {
private record EntityLoggingEntry(String prefix, double sampleRate, BytesQuantity maxEntitySize) {}
private final SslClientAuth clientAuth;
private final List<String> tlsCiphersOverride;
private final boolean proxyProtocolEnabled;
private final Duration endpoin... |
Is it indeterminate what is thrown? | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
try {
java.nio.file.Path tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.move(tempDir, prep... | } catch (AccessDeniedException | DirectoryNotEmptyException e) { | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
try {
java.nio.file.Path tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.move(tempDir, prep... | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} |
Test just randomly failed, and it would be nice to know why. Not related to this. | void consumer_is_propagated_to_metrics_proxy_api() {
String response = testDriver.sendRequest(VALUES_URI + consumerQuery(CUSTOM_CONSUMER)).readAll();
assertTrue(response.contains(REPLACED_CPU_METRIC), response);
} | assertTrue(response.contains(REPLACED_CPU_METRIC), response); | void consumer_is_propagated_to_metrics_proxy_api() {
String response = testDriver.sendRequest(VALUES_URI + consumerQuery(CUSTOM_CONSUMER)).readAll();
assertTrue(response.contains(REPLACED_CPU_METRIC), response);
} | class PrometheusV1HandlerTest {
private static final String URI_BASE = "http:
private static final String V1_URI = URI_BASE + PrometheusV1Handler.V1_PATH;
private static final String VALUES_URI = URI_BASE + PrometheusV1Handler.VALUES_PATH;
private static final String MOCK_METRICS_PATH = "/node0";
private static final S... | class PrometheusV1HandlerTest {
private static final String URI_BASE = "http:
private static final String V1_URI = URI_BASE + PrometheusV1Handler.V1_PATH;
private static final String VALUES_URI = URI_BASE + PrometheusV1Handler.VALUES_PATH;
private static final String MOCK_METRICS_PATH = "/node0";
private static final S... |
There are 2 possible failures: * Creating a temp dir fails => AccessDeniedException * Temp dir is on another partition/file system than destination, fails when doing `move` => DirectoryNotEmptyException (yes, strange) The first one happens when preprocessing a standalone container's application package, where we somet... | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
try {
java.nio.file.Path tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.move(tempDir, prep... | } catch (AccessDeniedException | DirectoryNotEmptyException e) { | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
try {
java.nio.file.Path tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.move(tempDir, prep... | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} |
Just to avoid looking up a path which never exists at this time. | public void createNewSession(Instant createTime) {
CuratorTransaction transaction = new CuratorTransaction(curator);
transaction.add(CuratorOperations.create(sessionPath.getAbsolute()));
transaction.add(CuratorOperations.create(sessionPath.append(UPLOAD_BARRIER).getAbsolute()));
transaction.add(CuratorOperations.create... | transaction.add(CuratorOperations.create(sessionStatusPath.getAbsolute(), Utf8.toBytes(Status.NEW.name()))); | public void createNewSession(Instant createTime) {
CuratorTransaction transaction = new CuratorTransaction(curator);
transaction.add(CuratorOperations.create(sessionPath.getAbsolute()));
transaction.add(CuratorOperations.create(sessionPath.append(UPLOAD_BARRIER).getAbsolute()));
transaction.add(CuratorOperations.create... | class SessionZooKeeperClient {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(SessionZooKeeperClient.class.getName());
private final Curator curator;
private final TenantName tenantName;
private final long sessionId;
private final Path sessionPath;
private final Path sessionStatu... | class SessionZooKeeperClient {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(SessionZooKeeperClient.class.getName());
private final Curator curator;
private final TenantName tenantName;
private final long sessionId;
private final Path sessionPath;
private final Path sessionStatu... |
Static import? | private InvalidJsonException createInvalidTypeException(Type... expected) {
var expectedTypesString = Arrays.stream(expected).map(this::toString)
.collect(java.util.stream.Collectors.joining("' or '", "'", "'"));
var pathString = path.isEmpty() ? "JSON" : "JSON member '%s'".formatted(path);
return new InvalidJsonExcept... | .collect(java.util.stream.Collectors.joining("' or '", "'", "'")); | private InvalidJsonException createInvalidTypeException(Type... expected) {
var expectedTypesString = Arrays.stream(expected).map(this::toString)
.collect(java.util.stream.Collectors.joining("' or '", "'", "'"));
var pathString = path.isEmpty() ? "JSON" : "JSON member '%s'".formatted(path);
return new InvalidJsonExcept... | class Json implements Iterable<Json> {
private final Inspector inspector;
private final String path;
public static Json of(Slime slime) { return of(slime.get()); }
public static Json of(Inspector inspector) { return new Json(inspector, ""); }
public static Json of(String json) { return of(SlimeUtils.jsonToSlime(json));... | class Json implements Iterable<Json> {
private final Inspector inspector;
private final String path;
public static Json of(Slime slime) { return of(slime.get()); }
public static Json of(Inspector inspector) { return new Json(inspector, ""); }
public static Json of(String json) { return of(SlimeUtils.jsonToSlime(json));... |
Should you remove this one and always do the cleanup in the finally clause, if not I guess you should set tempDir to null here too. | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
java.nio.file.Path tempDir = null;
try {
tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.mo... | IOUtils.recursiveDeleteDir(tempDir.toFile()); | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
java.nio.file.Path tempDir = null;
try {
tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.mo... | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} |
Actually the deletion will naturally be done in the finally, so this statement can be removed. | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
java.nio.file.Path tempDir = null;
try {
tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.mo... | IOUtils.recursiveDeleteDir(tempDir.toFile()); | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
java.nio.file.Path tempDir = null;
try {
tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.mo... | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} |
Yes, I didn't intend this one to be there, mixed up when editing, will fix | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
java.nio.file.Path tempDir = null;
try {
tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.mo... | IOUtils.recursiveDeleteDir(tempDir.toFile()); | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
java.nio.file.Path tempDir = null;
try {
tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.mo... | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} |
See comment below | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
java.nio.file.Path tempDir = null;
try {
tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.mo... | IOUtils.recursiveDeleteDir(tempDir.toFile()); | public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException {
java.nio.file.Path tempDir = null;
try {
tempDir = Files.createTempDirectory(appDir.getParentFile().toPath(), "preprocess-tempdir");
preprocess(appDir, tempDir.toFile(), zone);
IOUtils.recursiveDeleteDir(preprocessedDir);
Files.mo... | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} | class Component {
public final ComponentInfo info;
private final Bundle bundle;
public Component(Bundle bundle, ComponentInfo info) {
this.bundle = bundle;
this.info = info;
}
public List<Bundle.DefEntry> getDefEntries() {
return bundle.getDefEntries();
}
public Bundle getBundle() {
return bundle;
}
} |
Consider adding the tensor type to the exception message. | static void fillTensor(TokenBuffer buffer, TensorFieldValue tensorFieldValue) {
Tensor.Builder builder = Tensor.Builder.of(tensorFieldValue.getDataType().getTensorType());
if (buffer.current() == JsonToken.VALUE_STRING
&& builder instanceof IndexedTensor.BoundBuilder indexedBuilder)
{
double[] decoded = decodeHexString... | throw new IllegalArgumentException("Bad string input for tensor"); | static void fillTensor(TokenBuffer buffer, TensorFieldValue tensorFieldValue) {
Tensor.Builder builder = Tensor.Builder.of(tensorFieldValue.getDataType().getTensorType());
if (buffer.current() == JsonToken.VALUE_STRING
&& builder instanceof IndexedTensor.BoundBuilder indexedBuilder)
{
double[] decoded = decodeHexString... | class TensorReader {
public static final String TENSOR_TYPE = "type";
public static final String TENSOR_ADDRESS = "address";
public static final String TENSOR_CELLS = "cells";
public static final String TENSOR_VALUES = "values";
public static final String TENSOR_BLOCKS = "blocks";
public static final String TENSOR_VALU... | class TensorReader {
public static final String TENSOR_TYPE = "type";
public static final String TENSOR_ADDRESS = "address";
public static final String TENSOR_CELLS = "cells";
public static final String TENSOR_VALUES = "values";
public static final String TENSOR_BLOCKS = "blocks";
public static final String TENSOR_VALU... |
Is this change intentional? | public void testInvalidFieldWithoutFieldsFieldShouldFailParse() {
String jsonData = """
[
{
"remove": "id:unittest:smoke::whee",
"what is love": "baby, do not hurt me... much
}
]""";
new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next();
} | ]"""; | public void testInvalidFieldWithoutFieldsFieldShouldFailParse() {
String jsonData = """
[
{
"remove": "id:unittest:smoke::whee",
"what is love": "baby, do not hurt me... much
}
]""";
new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next();
} | class JsonReaderTestCase {
private DocumentTypeManager types;
private JsonFactory parserFactory;
@Before
public void setUp() throws Exception {
parserFactory = new JsonFactory();
types = new DocumentTypeManager();
{
DocumentType x = new DocumentType("smoke");
x.addField(new Field("something", DataType.STRING));
x.addFi... | class JsonReaderTestCase {
private DocumentTypeManager types;
private JsonFactory parserFactory;
@Before
public void setUp() throws Exception {
parserFactory = new JsonFactory();
types = new DocumentTypeManager();
{
DocumentType x = new DocumentType("smoke");
x.addField(new Field("something", DataType.STRING));
x.addFi... |
yes (syntax highlighting was confused by unbalanced quotes) | public void testInvalidFieldWithoutFieldsFieldShouldFailParse() {
String jsonData = """
[
{
"remove": "id:unittest:smoke::whee",
"what is love": "baby, do not hurt me... much
}
]""";
new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next();
} | ]"""; | public void testInvalidFieldWithoutFieldsFieldShouldFailParse() {
String jsonData = """
[
{
"remove": "id:unittest:smoke::whee",
"what is love": "baby, do not hurt me... much
}
]""";
new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next();
} | class JsonReaderTestCase {
private DocumentTypeManager types;
private JsonFactory parserFactory;
@Before
public void setUp() throws Exception {
parserFactory = new JsonFactory();
types = new DocumentTypeManager();
{
DocumentType x = new DocumentType("smoke");
x.addField(new Field("something", DataType.STRING));
x.addFi... | class JsonReaderTestCase {
private DocumentTypeManager types;
private JsonFactory parserFactory;
@Before
public void setUp() throws Exception {
parserFactory = new JsonFactory();
types = new DocumentTypeManager();
{
DocumentType x = new DocumentType("smoke");
x.addField(new Field("something", DataType.STRING));
x.addFi... |
Add unit test with `V5SignedIdentityDocument`? | void generates_and_validates_signature() {
IdentityDocumentSigner signer = new IdentityDocumentSigner();
IdentityDocument identityDocument = new IdentityDocument(
id, providerService, configserverHostname,
instanceHostname, createdAt, ipAddresses, identityType, clusterType, ztsUrl, serviceIdentity);
String data = Entit... | SignedIdentityDocument signedIdentityDocument = new V4SignedIdentityDocument( | void generates_and_validates_signature() {
IdentityDocumentSigner signer = new IdentityDocumentSigner();
IdentityDocument identityDocument = new IdentityDocument(
id, providerService, configserverHostname,
instanceHostname, createdAt, ipAddresses, identityType, clusterType, ztsUrl, serviceIdentity);
String data = Entit... | class IdentityDocumentSignerTest {
public static final int KEY_VERSION = 0;
private static final IdentityType identityType = TENANT;
private static final VespaUniqueInstanceId id =
new VespaUniqueInstanceId(1, "cluster-id", "instance", "application", "tenant", "region", "environment", identityType);
private static fina... | class IdentityDocumentSignerTest {
public static final int KEY_VERSION = 0;
private static final IdentityType identityType = TENANT;
private static final VespaUniqueInstanceId id =
new VespaUniqueInstanceId(1, "cluster-id", "instance", "application", "tenant", "region", "environment", identityType);
private static fina... |
```suggestion Paths.get(Defaults.getDefaults().underVespaHome("var/secure/proxy_cert.pem")), Paths.get(Defaults.getDefaults().underVespaHome("var/secure/proxy_key.pem")) ``` | public DataplaneProxyCredentials() {
this(
Paths.get(Defaults.getDefaults().underVespaHome("var/proxy/proxy_cert.pem")),
Paths.get(Defaults.getDefaults().underVespaHome("var/proxy/proxy_key.pem"))
);
} | Paths.get(Defaults.getDefaults().underVespaHome("var/proxy/proxy_key.pem")) | public DataplaneProxyCredentials() {
this(
Paths.get(Defaults.getDefaults().underVespaHome("secure/proxy_cert.pem")),
Paths.get(Defaults.getDefaults().underVespaHome("secure/proxy_key.pem"))
);
} | class DataplaneProxyCredentials extends AbstractComponent {
private static final Logger log = Logger.getLogger(DataplaneProxyCredentials.class.getName());
private final Path certificateFile;
private final Path keyFile;
private final X509Certificate certificate;
@Inject
public DataplaneProxyCredentials(Path certificateF... | class DataplaneProxyCredentials extends AbstractComponent {
private static final Logger log = Logger.getLogger(DataplaneProxyCredentials.class.getName());
private final Path certificateFile;
private final Path keyFile;
private final X509Certificate certificate;
@Inject
public DataplaneProxyCredentials(Path certificateF... |
Maybe we should output two different messages depending on the reason so that people get why it's disabled even if they themselves have enabled it? | public Autoscaling autoscale(Application application, Cluster cluster, NodeList clusterNodes, boolean enabled, boolean logDetails) {
var limits = Limits.of(cluster);
var model = model(application, cluster, clusterNodes);
if (model.isEmpty()) return Autoscaling.empty();
if (!enabled || (! limits.isEmpty() && cluster.min... | return Autoscaling.dontScale(Autoscaling.Status.unavailable, "Autoscaling is not enabled", model); | public Autoscaling autoscale(Application application, Cluster cluster, NodeList clusterNodes, boolean enabled, boolean logDetails) {
var limits = Limits.of(cluster);
var model = model(application, cluster, clusterNodes);
if (model.isEmpty()) return Autoscaling.empty();
boolean disabledByUser = !limits.isEmpty() && clus... | class Autoscaler {
private static final Logger log = Logger.getLogger(Autoscaler.class.getName());
/** What cost difference is worth a reallocation? */
private static final double costDifferenceWorthReallocation = 0.1;
/** What resource difference is worth a reallocation? */
private static final double resourceIncrease... | class Autoscaler {
private static final Logger log = Logger.getLogger(Autoscaler.class.getName());
/** What cost difference is worth a reallocation? */
private static final double costDifferenceWorthReallocation = 0.1;
/** What resource difference is worth a reallocation? */
private static final double resourceIncrease... |
Consider instead something like `"For schema 'X', fieldset 'Y': tensor fields ['foo', 'bar'] cannot be mixed with non-tensor fields ['baz', 'zoid'] in the same fieldset. See https://docs.vespa.ai/en/reference/schema-reference.html#fieldset"` | private void checkTypes(Schema schema, FieldSet fieldSet) {
var tensorFields = new LinkedList<String>();
var nonTensorFields = new LinkedList<String>();
for (String fieldName : fieldSet.getFieldNames()) {
ImmutableSDField field = schema.getField(fieldName);
if (field.getDataType() instanceof TensorDataType) {
tensorFie... | "and non-tensor fields ['" + String.join("','", nonTensorFields) + "']"); | private void checkTypes(Schema schema, FieldSet fieldSet) {
var tensorFields = new LinkedList<String>();
var nonTensorFields = new LinkedList<String>();
for (String fieldName : fieldSet.getFieldNames()) {
ImmutableSDField field = schema.getField(fieldName);
if (field.getDataType() instanceof TensorDataType) {
tensorFie... | class FieldSetSettings extends Processor {
public FieldSetSettings(Schema schema,
DeployLogger deployLogger,
RankProfileRegistry rankProfileRegistry,
QueryProfiles queryProfiles) {
super(schema, deployLogger, rankProfileRegistry, queryProfiles);
}
@Override
public void process(boolean validate, boolean documentsOnly) {... | class FieldSetSettings extends Processor {
private static String fieldSetDocUrl = "https:
public FieldSetSettings(Schema schema,
DeployLogger deployLogger,
RankProfileRegistry rankProfileRegistry,
QueryProfiles queryProfiles) {
super(schema, deployLogger, rankProfileRegistry, queryProfiles);
}
@Override
public void pro... |
Consider including the original exception as cause to the new `RuntimeException` instance. | private void handleHttpException(Throwable exception, CompletionContext context, int attempt) {
if (shouldRetry(exception)) {
if (attempt < MAX_RETRIES) {
waitBeforeRetry();
completeAsyncAttempt(context, attempt + 1);
} else {
context.completionFuture().completeExceptionally(new RuntimeException("OpenAI: max retries re... | context.completionFuture().completeExceptionally(new RuntimeException("OpenAI: max retries reached")); | private void handleHttpException(Throwable exception, CompletionContext context, int attempt) {
if (shouldRetry(exception)) {
if (attempt < MAX_RETRIES) {
waitBeforeRetry();
completeAsyncAttempt(context, attempt + 1);
} else {
context.completionFuture().completeExceptionally(new RuntimeException("OpenAI: max retries re... | class OpenAiClient implements LanguageModel {
private static final String DEFAULT_MODEL = "gpt-3.5-turbo";
private static final String DATA_FIELD = "data: ";
private static final int MAX_RETRIES = 3;
private static final long RETRY_DELAY_MS = 250;
private static final String OPTION_MODEL = "model";
private static final... | class OpenAiClient implements LanguageModel {
private static final String DEFAULT_MODEL = "gpt-3.5-turbo";
private static final String DATA_FIELD = "data: ";
private static final int MAX_RETRIES = 3;
private static final long RETRY_DELAY_MS = 250;
private static final String OPTION_MODEL = "model";
private static final... |
Thanks! | private void handleHttpException(Throwable exception, CompletionContext context, int attempt) {
if (shouldRetry(exception)) {
if (attempt < MAX_RETRIES) {
waitBeforeRetry();
completeAsyncAttempt(context, attempt + 1);
} else {
context.completionFuture().completeExceptionally(new RuntimeException("OpenAI: max retries re... | context.completionFuture().completeExceptionally(new RuntimeException("OpenAI: max retries reached")); | private void handleHttpException(Throwable exception, CompletionContext context, int attempt) {
if (shouldRetry(exception)) {
if (attempt < MAX_RETRIES) {
waitBeforeRetry();
completeAsyncAttempt(context, attempt + 1);
} else {
context.completionFuture().completeExceptionally(new RuntimeException("OpenAI: max retries re... | class OpenAiClient implements LanguageModel {
private static final String DEFAULT_MODEL = "gpt-3.5-turbo";
private static final String DATA_FIELD = "data: ";
private static final int MAX_RETRIES = 3;
private static final long RETRY_DELAY_MS = 250;
private static final String OPTION_MODEL = "model";
private static final... | class OpenAiClient implements LanguageModel {
private static final String DEFAULT_MODEL = "gpt-3.5-turbo";
private static final String DATA_FIELD = "data: ";
private static final int MAX_RETRIES = 3;
private static final long RETRY_DELAY_MS = 250;
private static final String OPTION_MODEL = "model";
private static final... |
isDirectory => exists, so remove `path.exists()` ? | public static boolean deleteFile(File path) {
if (path.exists() && path.isDirectory()) {
File[] files = path.listFiles();
for (File value : files) {
if (value.isDirectory())
deleteFile(value);
else
value.delete();
}
}
return(path.delete());
} | if (path.exists() && path.isDirectory()) { | public static boolean deleteFile(File path) {
if (path.isDirectory()) {
File[] files = path.listFiles();
for (File value : files) {
if (value.isDirectory())
deleteFile(value);
else
value.delete();
}
}
return(path.delete());
} | class FilesApplicationFile extends ApplicationFile {
private static final Logger log = Logger.getLogger("FilesApplicationFile");
private final File file;
private final ObjectMapper mapper = new ObjectMapper();
public FilesApplicationFile(Path path, File file) {
super(path);
this.file = file;
}
@Override
public boolean ... | class FilesApplicationFile extends ApplicationFile {
private static final Logger log = Logger.getLogger("FilesApplicationFile");
private final File file;
private final ObjectMapper mapper = new ObjectMapper();
public FilesApplicationFile(Path path, File file) {
super(path);
this.file = file;
}
@Override
public boolean ... |
I believe this `delete()` can only be invoked on a directory if the directory only has entries that start with `.`, and in that case any such file and directory-trees are deleted. This seems strange to me - does it make sense to you? It is possibly related to the fact that this class creates a .meta directory after d... | public ApplicationFile delete() {
if (file.isDirectory()) {
if (!listFiles().isEmpty())
throw new RuntimeException("Can't delete, directory not empty: " + this + "(" + listFiles() + ")." + listFiles().size());
var files = file.listFiles();
if (files != null) {
for (File f : files) {
deleteFile(f);
}
}
}
if (!file.delet... | if (!listFiles().isEmpty()) | public ApplicationFile delete() {
if (file.isDirectory()) {
if (!listFiles().isEmpty())
throw new RuntimeException("Can't delete, directory not empty: " + this + "(" + listFiles() + ")." + listFiles().size());
var files = file.listFiles();
if (files != null) {
for (File f : files) {
deleteFile(f);
}
}
}
if (!file.delet... | class FilesApplicationFile extends ApplicationFile {
private static final Logger log = Logger.getLogger("FilesApplicationFile");
private final File file;
private final ObjectMapper mapper = new ObjectMapper();
public FilesApplicationFile(Path path, File file) {
super(path);
this.file = file;
}
@Override
public boolean ... | class FilesApplicationFile extends ApplicationFile {
private static final Logger log = Logger.getLogger("FilesApplicationFile");
private final File file;
private final ObjectMapper mapper = new ObjectMapper();
public FilesApplicationFile(Path path, File file) {
super(path);
this.file = file;
}
@Override
public boolean ... |
Fixed | public static boolean deleteFile(File path) {
if (path.exists() && path.isDirectory()) {
File[] files = path.listFiles();
for (File value : files) {
if (value.isDirectory())
deleteFile(value);
else
value.delete();
}
}
return(path.delete());
} | if (path.exists() && path.isDirectory()) { | public static boolean deleteFile(File path) {
if (path.isDirectory()) {
File[] files = path.listFiles();
for (File value : files) {
if (value.isDirectory())
deleteFile(value);
else
value.delete();
}
}
return(path.delete());
} | class FilesApplicationFile extends ApplicationFile {
private static final Logger log = Logger.getLogger("FilesApplicationFile");
private final File file;
private final ObjectMapper mapper = new ObjectMapper();
public FilesApplicationFile(Path path, File file) {
super(path);
this.file = file;
}
@Override
public boolean ... | class FilesApplicationFile extends ApplicationFile {
private static final Logger log = Logger.getLogger("FilesApplicationFile");
private final File file;
private final ObjectMapper mapper = new ObjectMapper();
public FilesApplicationFile(Path path, File file) {
super(path);
this.file = file;
}
@Override
public boolean ... |
Should the try-catch be per session, to avoid one failing session blocking deletion of others? Alternatively, use a random or time-dependent subset of sessions—perhaps the first 0.05, but in reverse creation time order? | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | } catch (Throwable e) { | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
Ah, they're in somewhat random order already, from being a hash set of longs ... and using reverse creation order potentially leaves older sessions hanging, of course. So some true randomness, then, or moving the try-catch down a step. | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | } catch (Throwable e) { | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
Perhaps simpler to `sessions.removeAll(newSessions)` outside the loop? | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | if (newSessions.contains(sessionId)) continue; | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
Well, this fits with the below `continue`, so perhaps not ... | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | if (newSessions.contains(sessionId)) continue; | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
I'd think `canBeDeleted` is always true here, unless there's a race, which we don't want? | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | log.log(Level.FINE, () -> "expired: " + hasExpired + ", can be deleted: " + canBeDeleted(sessionId, status)); | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
Looks like a redundant log line, with the logging a few lines up? | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | log.log(Level.FINE, () -> "expired: " + hasExpired + ", can be deleted: " + canBeDeleted(sessionId, status)); | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
Could expiration time ever exceed 1 day? If it does, this becomes a bit weird—it's not "expired", but we attempt forceful deletion anyway. | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | } else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) { | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
Are these expected states? | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | if (applicationId.isEmpty()) continue; | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
So I guess this is racy: status and active-session are written in one transaction, but here we read them one after the other, so we could potentially see `PREPARED` and `true` (or `ACTIVATE` and `false`), and then go on to delete the remote session, if it had spent a long time in prepare (not impossible when a session ... | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | deleted++; | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
I wonder if we should also bail out if they disagree, unless the session `isOldAndCanBeDeleted(...)`, like for local sessions? | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | deleted++; | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
Do you remember how we could end up in this state? | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | |
Hmm, we could also read the session status as `PREPARED`, and active as `false`, but then the session is activated while we delete it. I don't remember without looking at the code, but I believe those writes are protected by a lock. Alternatively, we could do the deletion with a zknode version condition ... which I'm n... | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | deleted++; | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
Will do this while holding session lock instead | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | deleted++; | public void deleteExpiredRemoteAndLocalSessions(Clock clock, Predicate<Session> sessionIsActiveForApplication) {
Set<Long> sessions = getLocalSessionsIdsFromFileSystem();
sessions.addAll(getRemoteSessionsFromZooKeeper());
log.log(Level.FINE, () -> "Sessions for tenant " + tenantName + ": " + sessions);
Set<Long> newSes... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
pri... |
I would log after downloadFromSource and include the return value in the log message. | private void setFileReferencesToDownload(Request req) {
req.detach();
rpcAuthorizer.authorizeFileRequest(req)
.thenRun(() -> {
String[] fileReferenceStrings = req.parameters().get(0).asStringArray();
var client = req.target();
var peerSpec = client.peerSpec();
Stream.of(fileReferenceStrings)
.map(FileReference::new)
.f... | log.log(FINE, "Downloading file reference " + fileReference.value() + " from " + peerSpec); | private void setFileReferencesToDownload(Request req) {
req.detach();
rpcAuthorizer.authorizeFileRequest(req)
.thenRun(() -> {
String[] fileReferenceStrings = req.parameters().get(0).asStringArray();
var client = req.target();
var peerSpec = client.peerSpec();
Stream.of(fileReferenceStrings)
.map(FileReference::new)
.f... | class ChunkedFileReceiver implements FileServer.Receiver {
final Target target;
ChunkedFileReceiver(Target target) {
this.target = target;
}
@Override
public String toString() {
return target.toString();
}
@Override
public void receive(FileReferenceData fileData, FileServer.ReplayStatus status) {
int session = sendMeta... | class ChunkedFileReceiver implements FileServer.Receiver {
final Target target;
ChunkedFileReceiver(Target target) {
this.target = target;
}
@Override
public String toString() {
return target.toString();
}
@Override
public void receive(FileReferenceData fileData, FileServer.ReplayStatus status) {
int session = sendMeta... |
Yes, good idea, done | private void setFileReferencesToDownload(Request req) {
req.detach();
rpcAuthorizer.authorizeFileRequest(req)
.thenRun(() -> {
String[] fileReferenceStrings = req.parameters().get(0).asStringArray();
var client = req.target();
var peerSpec = client.peerSpec();
Stream.of(fileReferenceStrings)
.map(FileReference::new)
.f... | log.log(FINE, "Downloading file reference " + fileReference.value() + " from " + peerSpec); | private void setFileReferencesToDownload(Request req) {
req.detach();
rpcAuthorizer.authorizeFileRequest(req)
.thenRun(() -> {
String[] fileReferenceStrings = req.parameters().get(0).asStringArray();
var client = req.target();
var peerSpec = client.peerSpec();
Stream.of(fileReferenceStrings)
.map(FileReference::new)
.f... | class ChunkedFileReceiver implements FileServer.Receiver {
final Target target;
ChunkedFileReceiver(Target target) {
this.target = target;
}
@Override
public String toString() {
return target.toString();
}
@Override
public void receive(FileReferenceData fileData, FileServer.ReplayStatus status) {
int session = sendMeta... | class ChunkedFileReceiver implements FileServer.Receiver {
final Target target;
ChunkedFileReceiver(Target target) {
this.target = target;
}
@Override
public String toString() {
return target.toString();
}
@Override
public void receive(FileReferenceData fileData, FileServer.ReplayStatus status) {
int session = sendMeta... |
Consider adding a helper function that extracts the DocumentFrequency from the result, to avoid these 3 lines being duplicated in all test cases. | public void testSignificanceSearcherWithMissingExplicitLanguageOnExistingWord() {
var existingWord = "hello";
var explicitLanguage = Language.ITALIAN;
var result = searchWordWithLanguage(existingWord, Optional.of(explicitLanguage), Optional.empty());
var resultRoot = (AndItem) result.getQuery().getModel().getQueryTree(... | var resultRoot = (AndItem) result.getQuery().getModel().getQueryTree().getRoot(); | public void testSignificanceSearcherWithMissingExplicitLanguageOnExistingWord() {
var existingWord = "hello";
var explicitLanguage = Language.ITALIAN;
var result = searchWord(existingWord, Optional.of(explicitLanguage), Optional.empty());
var resultWord = getFirstWord(result);
assertEquals(Optional.empty(), resultWord.... | class MockDetector implements Detector {
private Language detectionLanguage;
MockDetector(Language detectionLanguage) {
this.detectionLanguage = detectionLanguage;
}
@Override
public Detection detect(byte[] input, int offset, int length, Hint hint) {
throw new UnsupportedOperationException("Not implemented");
}
@Overri... | class MockDetector implements Detector {
private Language detectionLanguage;
MockDetector(Language detectionLanguage) {
this.detectionLanguage = detectionLanguage;
}
@Override
public Detection detect(byte[] input, int offset, int length, Hint hint) {
throw new UnsupportedOperationException("Not implemented");
}
@Overri... |
Makes sense. Extracted two methods and removed duplication. | public void testSignificanceSearcherWithMissingExplicitLanguageOnExistingWord() {
var existingWord = "hello";
var explicitLanguage = Language.ITALIAN;
var result = searchWordWithLanguage(existingWord, Optional.of(explicitLanguage), Optional.empty());
var resultRoot = (AndItem) result.getQuery().getModel().getQueryTree(... | var resultRoot = (AndItem) result.getQuery().getModel().getQueryTree().getRoot(); | public void testSignificanceSearcherWithMissingExplicitLanguageOnExistingWord() {
var existingWord = "hello";
var explicitLanguage = Language.ITALIAN;
var result = searchWord(existingWord, Optional.of(explicitLanguage), Optional.empty());
var resultWord = getFirstWord(result);
assertEquals(Optional.empty(), resultWord.... | class MockDetector implements Detector {
private Language detectionLanguage;
MockDetector(Language detectionLanguage) {
this.detectionLanguage = detectionLanguage;
}
@Override
public Detection detect(byte[] input, int offset, int length, Hint hint) {
throw new UnsupportedOperationException("Not implemented");
}
@Overri... | class MockDetector implements Detector {
private Language detectionLanguage;
MockDetector(Language detectionLanguage) {
this.detectionLanguage = detectionLanguage;
}
@Override
public Detection detect(byte[] input, int offset, int length, Hint hint) {
throw new UnsupportedOperationException("Not implemented");
}
@Overri... |
Unintentional added indent? | public record BucketKeyWrapper(long key) implements Comparable<BucketKeyWrapper> {
public int compareTo(BucketKeyWrapper other) {
if ((key & 0x8000000000000000L) != (other.key & 0x8000000000000000L)) {
return ((key >>> 63) > (other.key >>> 63)) ? 1 : -1;
}
if ((key & 0x7FFFFFFFFFFFFFFFL) < (other.key & 0x7FFFFFFFFFFFFF... | if ((key & 0x8000000000000000L) != (other.key & 0x8000000000000000L)) { | public record BucketKeyWrapper(long key) implements Comparable<BucketKeyWrapper> {
public int compareTo(BucketKeyWrapper other) {
if ((key & 0x8000000000000000L) != (other.key & 0x8000000000000000L)) {
return ((key >>> 63) > (other.key >>> 63)) ? 1 : -1;
}
if ((key & 0x7FFFFFFFFFFFFFFFL) < (other.key & 0x7FFFFFFFFFFFFF... | class BucketEntry {
private BucketId progress;
private BucketState state;
private BucketEntry(BucketId progress, BucketState state) {
this.progress = progress;
this.state = state;
}
public BucketId getProgress() {
return progress;
}
public void setProgress(BucketId progress) {
this.progress = progress;
}
public BucketS... | class BucketEntry {
private BucketId progress;
private BucketState state;
private BucketEntry(BucketId progress, BucketState state) {
this.progress = progress;
this.state = state;
}
public BucketId getProgress() {
return progress;
}
public void setProgress(BucketId progress) {
this.progress = progress;
}
public BucketS... |
fixed | public record BucketKeyWrapper(long key) implements Comparable<BucketKeyWrapper> {
public int compareTo(BucketKeyWrapper other) {
if ((key & 0x8000000000000000L) != (other.key & 0x8000000000000000L)) {
return ((key >>> 63) > (other.key >>> 63)) ? 1 : -1;
}
if ((key & 0x7FFFFFFFFFFFFFFFL) < (other.key & 0x7FFFFFFFFFFFFF... | if ((key & 0x8000000000000000L) != (other.key & 0x8000000000000000L)) { | public record BucketKeyWrapper(long key) implements Comparable<BucketKeyWrapper> {
public int compareTo(BucketKeyWrapper other) {
if ((key & 0x8000000000000000L) != (other.key & 0x8000000000000000L)) {
return ((key >>> 63) > (other.key >>> 63)) ? 1 : -1;
}
if ((key & 0x7FFFFFFFFFFFFFFFL) < (other.key & 0x7FFFFFFFFFFFFF... | class BucketEntry {
private BucketId progress;
private BucketState state;
private BucketEntry(BucketId progress, BucketState state) {
this.progress = progress;
this.state = state;
}
public BucketId getProgress() {
return progress;
}
public void setProgress(BucketId progress) {
this.progress = progress;
}
public BucketS... | class BucketEntry {
private BucketId progress;
private BucketState state;
private BucketEntry(BucketId progress, BucketState state) {
this.progress = progress;
this.state = state;
}
public BucketId getProgress() {
return progress;
}
public void setProgress(BucketId progress) {
this.progress = progress;
}
public BucketS... |
For select constant, scanNodePlanFragmentParams is not empty? | private FragmentExecParams getMaxParallelismScanFragmentExecParams() {
List<FragmentExecParams> scanNodePlanFragmentParams =
this.scanNodes.stream().map(node -> fragmentExecParamsMap.get(node.getFragment().getFragmentId()))
.collect(Collectors.toList());
int maxParallelism = 0;
Preconditions.checkState(!scanNodePlanFra... | Preconditions.checkState(!scanNodePlanFragmentParams.isEmpty()); | private FragmentExecParams getMaxParallelismScanFragmentExecParams() {
List<FragmentExecParams> scanNodePlanFragmentParams =
this.scanNodes.stream().map(node -> fragmentExecParamsMap.get(node.getFragment().getFragmentId()))
.collect(Collectors.toList());
int maxParallelism = 0;
FragmentExecParams maxParallelismExecPara... | class Coordinator {
private static final Logger LOG = LogManager.getLogger(Coordinator.class);
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final String localIP = FrontendOptions.getLocalHostAddress();
private static final Random instanceRandom = new Random()... | class Coordinator {
private static final Logger LOG = LogManager.getLogger(Coordinator.class);
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final String localIP = FrontendOptions.getLocalHostAddress();
private static final Random instanceRandom = new Random()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.