IndexWriter allows updating index sort fields if the index sort is not set in the config
Description
If an index was written with an index sort, and is later opened by an IndexWriter whose config has no index sort, doc-values updates on the sort field are accepted. The same happens after addIndexes(Directory) of a sorted index into an unsorted writer.
The segments still say they are sorted by that field, but after the update their documents are no longer in that order. Code that trusts the segment sort then returns wrong results with no error:
- a sorted top-N search returns the wrong top hit (early termination)
- IndexSortSortedNumericDocValuesRangeQuery misses matching documents
The problem stays after a later merge, even by a writer that has the correct sort. CheckIndex at the slow level reports: "segment has indexSort=<long: "sort"> but docID=1998 sorts after docID=1999" The default CheckIndex level does not run this check.
Cause: validateIndexSort() skips everything when config.getIndexSort() is null, and the update guards only check config.getIndexSortFields(), not the sort recorded in each segment.
Steps to reproduce:
- Index 2000 docs with NumericDocValuesField("sort", i + 1) and setIndexSort(new Sort(new SortField("sort", SortField.Type.LONG))), then forceMerge(1)
- Open a new IndexWriter with a plain IndexWriterConfig (no index sort)
- updateNumericDocValue(term for the last doc, "sort", 0) -> no exception
- searcher.search(MatchAllDocsQuery.INSTANCE, 1, indexSort) returns sort=1, expected 0
I have a fix with tests and can open a PR.
Version and environment details
Lucene main at 18d5c42edb (also checked on current main), JDK 25 (Temurin 25.0.4.1), Linux (WSL2). Reproduces with assertions on and off.