{"record":{"id":"4a04b19b542c0d35","repo":"apache/beam","slug":"nlargest-keep-keep-r-is-not-supported-because-it-is-order","errorCode":null,"errorMessage":"nlargest(keep={keep!r}) is not supported because it is order sensitive. Only keep=\"all\" is supported.","messagePattern":"nlargest\\(keep=(.+?)\\) is not supported because it is order sensitive\\. Only keep=\"all\" is supported\\.","errorType":"exception","errorClass":"WontImplementError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/dataframe/frames.py","lineNumber":2203,"sourceCode":"  __contains__ = frame_base.wont_implement_method(\n      pd.Series, '__contains__', reason=\"non-deferred-result\")\n\n  @frame_base.with_docs_from(pd.Series)\n  @frame_base.args_to_kwargs(pd.Series)\n  @frame_base.populate_defaults(pd.Series)\n  def nlargest(self, keep, **kwargs):\n    \"\"\"Only ``keep=False`` and ``keep=\"any\"`` are supported. Other values of\n    ``keep`` make this an order-sensitive operation. Note ``keep=\"any\"`` is\n    a Beam-specific option that guarantees only one duplicate will be kept, but\n    unlike ``\"first\"`` and ``\"last\"`` it makes no guarantees about _which_\n    duplicate element is kept.\"\"\"\n    # TODO(robertwb): Document 'any' option.\n    # TODO(robertwb): Consider (conditionally) defaulting to 'any' if no\n    # explicit keep parameter is requested.\n    if keep == 'any':\n      keep = 'first'\n    elif keep != 'all':\n      raise frame_base.WontImplementError(\n          f\"nlargest(keep={keep!r}) is not supported because it is \"\n          \"order sensitive. Only keep=\\\"all\\\" is supported.\",\n          reason=\"order-sensitive\")\n    kwargs['keep'] = keep\n    per_partition = expressions.ComputedExpression(\n        'nlargest-per-partition', lambda df: df.nlargest(**kwargs),\n        [self._expr],\n        preserves_partition_by=partitionings.Arbitrary(),\n        requires_partition_by=partitionings.Arbitrary())\n    with expressions.allow_non_parallel_operations(True):\n      return frame_base.DeferredFrame.wrap(\n          expressions.ComputedExpression(\n              'nlargest', lambda df: df.nlargest(**kwargs), [per_partition],\n              preserves_partition_by=partitionings.Arbitrary(),\n              requires_partition_by=partitionings.Singleton()))\n\n  @frame_base.with_docs_from(pd.Series)\n  @frame_base.args_to_kwargs(pd.Series)","sourceCodeStart":2185,"sourceCodeEnd":2221,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/dataframe/frames.py#L2185-L2221","documentation":"DeferredDataFrame/Series.nlargest() with keep='first' or 'last' breaks ties by row order, which is undefined in a distributed Beam pipeline. Therefore only keep='all' (keep every tied row) is supported; any other value raises WontImplementError with reason 'order-sensitive'.","triggerScenarios":"Calling nlargest(n, keep='first'), keep='last', or keep='any' (note: keep='any' is silently converted to 'first', which then raises? No — 'any' is mapped to 'first'... actually 'any' is accepted and remapped, so the error fires for any keep value that is not 'any' or 'all', e.g. 'first', 'last', or a typo like 'all '.)","commonSituations":"Porting pandas nlargest(..., keep='first') defaults — pandas' default keep='first' will trigger this; typos in the keep value; code that relies on tie-breaking order.","solutions":["Pass keep='all' explicitly: nlargest(n, keep='all')","Avoid relying on tie-break order; deduplicate afterwards if you need fewer rows","Use keep='any' (Beam-specific) which lets Beam keep an arbitrary duplicate","Sort by the column and slice head(n) only if order-insensitivity of ties is acceptable"],"exampleFix":"// before\ndf.nlargest(5, 'score')  # pandas default keep='first'\n// after\ndf.nlargest(5, 'score', keep='all')","handlingStrategy":"validation","validationCode":"assert keep == 'all', \"nlargest on Beam dataframes only supports keep='all' (or keep='any')\"","typeGuard":"def beam_safe_keep(keep):\n    return keep in ('all', 'any')","tryCatchPattern":"from apache_beam.dataframe import frame_base\ntry:\n    top = df.nlargest(n, col, keep='all')\nexcept frame_base.WontImplementError:\n    top = df.nlargest(n, col, keep='all')","preventionTips":["Always pass keep explicitly to nlargest/nsmallest in Beam pipelines","Treat pandas defaults (keep='first') as unsafe in distributed code","Decide tie-handling policy (all vs any) before porting"],"tags":["pandas","apache-beam","dataframe","order-sensitive"],"backgroundTag":"invalid-enum-value","analyzedSha":"12126d8942aaf848030c478b4c6a28c6af861c66","analyzedAt":"2026-09-13T01:50:10.254Z","contentChangedAt":"2026-09-13T01:50:10.254Z","schemaVersion":2},"datasetVersion":"2026-09-20T03:17:13.778Z"}